3 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
其他答案現(xiàn)在已經(jīng)過(guò)時(shí)了。我必須自己解決這個(gè)問(wèn)題,所以這是我發(fā)現(xiàn)的。
你的錯(cuò)誤在這里:
r.Use(middleware.Compress(5, "gzip"))
第二個(gè)參數(shù)(“類型”)是指將應(yīng)用壓縮的內(nèi)容類型。例如:"text/html"、"application/json"等
只需添加要壓縮的內(nèi)容類型列表,或完全刪除參數(shù):
func main() {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Use(middleware.Compress(5))
r.Get("/", Hello)
http.ListenAndServe(":3333", r)
}
這將壓縮middleware.compress中默認(rèn)列表中定義的所有內(nèi)容類型:
var defaultCompressibleContentTypes = []string{
"text/html",
"text/css",
"text/plain",
"text/javascript",
"application/javascript",
"application/x-javascript",
"application/json",
"application/atom+xml",
"application/rss+xml",
"image/svg+xml",
}
祝你好運(yùn)!

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
r.Use(middleware.DefaultCompress)現(xiàn)在已被標(biāo)記為DEPRECATED.
要啟用壓縮,您需要?jiǎng)?chuàng)建一個(gè)壓縮器并使用其處理程序。
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
compressor := middleware.NewCompressor(flate.DefaultCompression)
r.Use(compressor.Handler())
r.Get("/", Hello)
http.ListenAndServe(":3333", r)
該flate包必須導(dǎo)入為compress/flate.

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
使用注釋middleware.DefaultCompress和正常GET請(qǐng)求。
package main
import (
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
func main() {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Use(middleware.DefaultCompress)
r.Get("/", Hello)
http.ListenAndServe(":3333", r)
}
func Hello(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte("hello world\n"))
}
嘗試使用curl:
$ curl -v http://localhost:3333 --compressed
* Rebuilt URL to: http://localhost:3333/
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 3333 (#0)
> GET / HTTP/1.1
> Host: localhost:3333
> User-Agent: curl/7.58.0
> Accept: */*
> Accept-Encoding: deflate, gzip
>
< HTTP/1.1 200 OK
< Content-Encoding: gzip
< Content-Type: text/html
< Date: Sat, 31 Aug 2019 23:37:52 GMT
< Content-Length: 36
<
hello world
* Connection #0 to host localhost left intact
或者HTTPie:
$ http :3333
HTTP/1.1 200 OK
Content-Encoding: gzip
Content-Length: 36
Content-Type: text/html
Date: Sat, 31 Aug 2019 23:38:31 GMT
hello world
- 3 回答
- 0 關(guān)注
- 174 瀏覽
添加回答
舉報(bào)