英文:
Golang http.Response gzip writer ERR_CONTENT_LENGTH_MISMATCH
问题
我正在尝试对来自httputil.ReverseProxy的代理响应进行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。
英文:
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")
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")
Can anyone tell what i'm doing wrong? The content-length is always 10 even when the input changes.
答案1
得分: 3
你没有关闭gz
写入器,这可能是个问题。gzip.Writer
的文档中提到:
当完成写入操作后,调用方有责任调用WriteCloser的Close方法。写入的数据可能会被缓冲并在调用Close方法之前不会被刷新。
因此,在完成数据写入后,尝试添加gz.Close()
。
英文:
You're not closing your gz
writer. It's possible issue. gzip.Writer
documentation says:
> It is the caller's responsibility to call Close on the WriteCloser when done. Writes may be buffered and not flushed until Close.
So, try to add gz.Close()
after you've completed writing data.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论