问题描述
我正在尝试对httputil.ReverseProxy-> ModifyResponse中的代理响应进行gzip压缩.因此,我只能访问http.Response对象.
I'm trying to gzip the proxied response from httputil.ReverseProxy -> ModifyResponse.So I only have access to the http.Response object.
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错误.
This works just fine. But when I gzip the content I'll get a content-length-mismatch error.
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.
Can anyone tell what i'm doing wrong? The content-length is always 10 even when the input changes.
推荐答案
您没有关闭 gz
编写器.这可能是问题. gzip.Writer
文档说:
You're not closing your gz
writer. It's possible issue. gzip.Writer
documentation says:
因此,在完成数据写入后,尝试添加 gz.Close()
.
So, try to add gz.Close()
after you've completed writing data.
这篇关于Golang http.Response gzip编写器ERR_CONTENT_LENGTH_MISMATCH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!