Golang http.Response gzip编写器ERR_CONTENT_LENGTH_MISMATCH [英] Golang http.Response gzip writer ERR_CONTENT_LENGTH_MISMATCH

查看:49
本文介绍了Golang http.Response gzip编写器ERR_CONTENT_LENGTH_MISMATCH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对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:

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

It is the caller's responsibility to call Close on the WriteCloser when done. Writes may be buffered and not flushed until Close.

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

So, try to add gz.Close() after you've completed writing data.

这篇关于Golang http.Response gzip编写器ERR_CONTENT_LENGTH_MISMATCH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆