Golang:默认的HTTP客户端不处理压缩。

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

Golang: default HTTP client doesn't handle compression

问题

我正在尝试进行一个HTTP请求,并让golang自动添加accept-encoding头部,并在响应被压缩时自动解压缩。我原本以为默认的HTTP客户端应该可以透明地处理这个问题,但实际上并不是这样的:

req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
// req.Header.Add("Accept-Encoding", "gzip")
client := &http.Client{}
resp, _ := client.Do(req)
println(resp.Header.Get("Content-Encoding"))

如果我手动添加Accept-Encoding头部,它会发送这个头部,但我仍然需要手动解压缩响应。

英文:

I'm trying to do an HTTP request and have golang add accept-encoding header and decompress the response automatically if it is compressed. I was under the impression that the default HTTP client should handle it transparently? However it doesn't appear to:

	req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
	// req.Header.Add("Accept-Encoding", "gzip")
	client := &http.Client{}
	resp, _ := client.Do(req)
	println(resp.Header.Get("Content-Encoding"))

If I add the Accept-Encoding manually, it sends the header, but I have to uncompress the response manually.

答案1

得分: 5

如果传输请求自己请求gzip并获得了gzip压缩的响应,则响应会被透明地解压缩。在这种情况下,传输会从响应中删除Content-Encoding头部。

检查Response.Uncompressed字段以确定响应是否已解压缩。

req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
resp, _ := http.DefaultClient.Do(req)
fmt.Println(resp.Uncompressed) // 输出 true
fmt.Println(resp.Header.Get("Content-Encoding")) // 输出空行

如果应用程序明确请求gzip,则响应将原样返回。

req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
req.Header.Add("Accept-Encoding", "gzip")
client := &http.Client{}
resp, _ := client.Do(req)
fmt.Println(resp.Uncompressed) // 输出 false
fmt.Println(resp.Header.Get("Content-Encoding")) // 输出 gzip
英文:

If the Transport requests gzip on its own and gets a gzipped response, then the response is transparently decompressed. The transport removes the Content-Encoding header from the response in this case.
Check the Response. Uncompressed field to determine if the response was uncompressed.

req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
resp, _ := http.DefaultClient.Do(req)
fmt.Println(resp.Uncompressed) // prints true
fmt.Println(resp.Header.Get("Content-Encoding"))  // prints blank line

If the application explicitly requests gzip, then the response is returned as is.

req, _ := http.NewRequest("Get", "https://stackoverflow.com", nil)
req.Header.Add("Accept-Encoding", "gzip")  
client := &http.Client{}
resp, _ := client.Do(req)
fmt.Println(resp.Uncompressed)  // prints false
fmt.Println(resp.Header.Get("Content-Encoding")) prints gzip

huangapple
  • 本文由 发表于 2022年2月7日 04:17:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/71011274.html
匿名

发表评论

匿名网友

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

确定