可能与Go:检测gzip编码以手动解压缩响应,但“内容-编码”头丢失有关
我了解到,除非将Accept-Encoding: gzip设置为True,否则net/http传输会将DisableCompression添加到请求中,如果我希望它自动解压缩http响应,就需要这样做。在这种情况下,以下代码不接收Content-Encoding: gzip头:
https://play.golang.org/p/FWs5uG9pZEL (注意:由于网络限制,不会在操场上运行)
如果我运行本地服务器并使用它运行上面的代码,我可以看到预期的标头正在发送:
GET / HTTP/1.1
Host: localhost:5555
User-Agent: Go-http-client/1.1
Accept-Encoding: gzip连接go所创建的连接是否还会导致服务器不返回经过压缩的响应?
发布于 2019-12-01 13:14:02
Accept-Encoding: gzip只意味着客户端能够处理并愿意处理gzip压缩内容。并不意味着服务器必须实际压缩内容。事实上,例如,对于图像,用gzip压缩内容是没有意义的,因为这些已经是压缩的数据(但不是使用gzip),并且在顶部添加gzip实际上可能会增加有效负载的大小。
如果您希望您的服务器返回压缩内容,则实际上必须配置您的服务器才能做到这一点。例如,请参阅这里关于如何使用nginx实现此操作的内容。
请注意,http.Response将透明地解压缩响应,而http.Response将相应地更新头,即删除Content-Encoding。这意味着在检查resp.Header.Get("Content-Encoding")时不会得到原始的响应头resp.Header.Get("Content-Encoding")。如果响应被自动解压缩,可以在Uncompressed字段中看到:
fmt.Println("was compressed ", resp.Uncompressed)有关更多信息,请参见go doc http.Response
// Uncompressed reports whether the response was sent compressed but
// was decompressed by the http package. When true, reading from
// Body yields the uncompressed content instead of the compressed
// content actually set from the server, ContentLength is set to -1,
// and the "Content-Length" and "Content-Encoding" fields are deleted
// from the responseHeader. To get the original response from
// the server, set Transport.DisableCompression to true.
Uncompressed boolhttps://stackoverflow.com/questions/59125657
复制相似问题