Golang http.Response gzip writer ERR_CONTENT_LENGTH_MISMATCH

huangapple go评论85阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年6月18日 18:13:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/44613920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定