Golang http.Response gzip作家ERR_CONTENT_LENGTH_MISMATCH
问题描述:
我试图从httputil.ReverseProxy gzip代理响应 - > ModifyResponse。 所以我只能访问http.Response对象。Golang http.Response gzip作家ERR_CONTENT_LENGTH_MISMATCH
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")
这工作得很好。但是,当我压缩内容时,我会得到一个内容长度不匹配的错误。
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说:
完成后,调用者有责任在WriteCloser上调用Close。写入可能会被缓冲,直到关闭才会被刷新。
因此,在完成写入数据后尝试添加gz.Close()
。