Golang http.Response gzip 编写器 ERR_CONTENT_LENGTH_MISMATCH

Golang http.Response gzip writer ERR_CONTENT_LENGTH_MISMATCH

我正在尝试对来自 httputil.ReverseProxy -> ModifyResponse 的代理响应进行 gzip 压缩。 所以我只能访问 http.Response 对象。

res.Body = ioutil.NopCloser(bytes.NewReader(minified))
res.ContentLength = int64(len(minified))
res.Header.Set("Content-Length", strconv.Itoa(len(minified)))
res.Header.Del("Content-Encoding")

这很好用。但是,当我对内容进行 gzip 压缩时,会出现内容长度不匹配错误。

var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
gz.Write(minified)

readCloser := ioutil.NopCloser(&buf)
res.Body = readCloser

res.ContentLength = int64(buf.Len())
res.Header.Set("Content-Length", strconv.Itoa(buf.Len()))
res.Header.Set("Content-Encoding", "gzip")

谁能告诉我我做错了什么?即使输入发生变化,内容长度始终为 10。

您不会关闭您的 gz 作者。是可能的问题。 gzip.Writer documentation 说:

It is the caller's responsibility to call Close on the WriteCloser when done. Writes may be buffered and not flushed until Close.

所以,写完数据后尝试添加gz.Close()