我开始用 Go 编写服务器端应用程序。我想使用 Accept-Encoding
请求 header 来确定是否使用 GZIP
压缩响应实体。我曾希望找到一种直接使用 http.Serve
或 http.ServeFile
方法的方法。
这是一个相当普遍的要求;我错过了什么还是需要推出自己的解决方案?
最佳答案
《纽约时报》发布了他们的gzip middleware package for Go .
您只需通过他们的 GzipHandler
传递您的 http.HandlerFunc
即可。它看起来像这样:
package main
import (
"io"
"net/http"
"github.com/nytimes/gziphandler"
)
func main() {
withoutGz := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
io.WriteString(w, "Hello, World")
})
withGz := gziphandler.GzipHandler(withoutGz)
http.Handle("/", withGz)
http.ListenAndServe("0.0.0.0:8000", nil)
}
关于http - 为 Go 提供 gzip 压缩的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14073393/