http.ServeContent()【Go】
ファイルをサーバーにあげる際に利用します。
io.Copyと比較して、各種ヘッダー情報を付加、利用できる点で利があります。
それはContet-Range、MIMEタイプ、ETagを利用したIf-MatchとIf-None-Match、 If-Range、
さらにIf-Unmodified-Sinceなどで、正確に、かつより効率的なサービングを実現します。
func pict(w http.ResponseWriter, req *http.Request) { f, err := os.Open("pict.png") if err != nil { http.Error(w, "file not found", 404) } defer f.Close() fi, err := f.Stat() // ファイルの各情報をファイル構造体から取得する if err != nil { http.Error(w, "file not found", 404) } http.ServeContent(w, req, fi.Name(), fi.ModTime(), f) // Stat()により取得したファイル情報からName()とModTime()を利用 } func main() { http.HandleFunc("/", pict) // アクセスと同時にpictを実行 http.ListenAndServe(":8080", nil) }
http.ServeContentはファイル名、modtime(最終の修正日時)を引数に要求するため、
FileのメソッドであるStat()を使用して、ファイル情報を事前に取得しています。