繁体   English   中英

Golang http.Response gzip编写器ERR_CONTENT_LENGTH_MISMATCH

[英]Golang http.Response gzip writer ERR_CONTENT_LENGTH_MISMATCH

我正在尝试从httputil.ReverseProxy-> ModifyResponse中压缩代理响应。 因此,我只能访问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压缩时,会出现content-length-mismatch错误。

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 文档说:

完成后,调用方有责任在WriteCloser上调用Close。 写入可能会被缓冲,直到关闭才刷新。

因此,在完成数据写入后,尝试添加gz.Close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM