静的ファイル用の非常に単純なgzipミドルウェアを作成しようとしています。しかし、私はnext.ServeHTTP(w, r)
コード内の5つの場所を呼び出していますが、これを延期するとどうなりますか?返される関数が実行される前にこれが呼び出されますか?関数を返す関数の中で関数を延期するとどうなりますか?注文はどうですか?
これは私が持っているものです。
func gzipHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
// If for some weird reason client does not understand gzip, then continue.
next.ServeHTTP(w, r)
return
}
path := filepath.FromSlash(filepath.Join(cfg.PublicHTML, r.URL.Path))
if _, err := os.Stat(path); os.IsNotExist(err) {
// If file or folder does not exists, then continue.
next.ServeHTTP(w, r)
return
}
var ext string
for _, v := range cfg.GzipExt {
if strings.HasSuffix(r.URL.Path, v) {
ext = v
}
}
if ext == "" {
// This file should not be served as gzipped content.
next.ServeHTTP(w, r)
return
}
// Only serve gzipped file if it exists.
if _, err := os.Stat(path + ".gz"); os.IsNotExist(err) {
// TODO: Create the gzipped file.
// http://stackoverflow.com/questions/16890648/how-can-i-use-golangs-compress-gzip-package-to-gzip-a-file
next.ServeHTTP(w, r)
return
}
w.Header().Add("Content-Encoding", "gzip")
r.URL.Path = r.URL.Path + ".gz"
next.ServeHTTP(w, r)
})
}
それは(R、W)next.ServeHTTPを延期するためにここに可能でしょうか?このように:私はこのようなnext.ServeHTTP(R、W)を延期する場合は、その意志
router.NotFound = gzipHandler(fileServer())
:
func gzipHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer next.ServeHTTP(w, r)
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
// If for some weird reason client does not understand gzip, then continue.
return
}
path := filepath.FromSlash(filepath.Join(cfg.PublicHTML, r.URL.Path))
if _, err := os.Stat(path); os.IsNotExist(err) {
// If file or folder does not exists, then continue.
return
}
var ext string
for _, v := range cfg.GzipExt {
if strings.HasSuffix(r.URL.Path, v) {
ext = v
}
}
if ext == "" {
// This file should not be served as gzipped content.
return
}
// Only serve gzipped file if it exists.
if _, err := os.Stat(path + ".gz"); os.IsNotExist(err) {
// TODO: Create the gzipped file.
// http://stackoverflow.com/questions/16890648/how-can-i-use-golangs-compress-gzip-package-to-gzip-a-file
return
}
w.Header().Add("Content-Encoding", "gzip")
r.URL.Path = r.URL.Path + ".gz"
})
}
私は、静的なファイルを提供するために、このような私のmain()関数でこれを使用していますfileServer()が実行される前に実行されますか?関数呼び出しで
はい、deferはすべての終了パスで関数を呼び出します。したがって、可能です。間違いなく明らかではない。代わりに、大量のコードを別のcanGzip(要求)関数に抽出することを検討してください。 – Mark
canGzip(リクエスト)についてのアドバイスをありがとう!別の機能でそれらを包むことができたことは私には起こりませんでした。ありがとう! – Alex