为什么HTTP客户端强制使用Accept-Encoding标头 [英] Why does the HTTP Client Force an Accept-Encoding header
问题描述
示例代码:
package main
import (
"fmt"
"net/http"
"net/http/httputil"
)
func main() {
client := &http.Client{
Transport: &http.Transport{
DisableCompression: true,
},
}
url := "https://google.com"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return
}
//req.Header.Set("Accept-Encoding", "*")
//req.Header.Del("Accept-Encoding")
requestDump, err := httputil.DumpRequestOut(req, false)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(requestDump))
client.Do(req)
}
输出:
GET / HTTP/1.1
Host: google.com
User-Agent: Go-http-client/1.1
Accept-Encoding: gzip
仅使用 req.Header.Set("Accept-Encoding","*"
不加注释:
GET / HTTP/1.1
Host: google.com
User-Agent: Go-http-client/1.1
Accept-Encoding: *
仅使用 req.Header.Del("Accept-Encoding")
取消注释:
GET / HTTP/1.1
Host: google.com
User-Agent: Go-http-client/1.1
Accept-Encoding: gzip
两行都未注释:
GET / HTTP/1.1
Host: google.com
User-Agent: Go-http-client/1.1
Accept-Encoding: gzip
DisableCompression
确实对HTTP请求本身有任何作用吗?根据godocs:
Does DisableCompression
actually do anything to the HTTP Request itself?
According to the godocs:
// DisableCompression, if true, prevents the Transport from
// requesting compression with an "Accept-Encoding: gzip"
// request header when the Request contains no existing
// Accept-Encoding value. If the Transport requests gzip on
// its own and gets a gzipped response, it's transparently
// decoded in the Response.Body. However, if the user
// explicitly requested gzip it is not automatically
// uncompressed.
推荐答案
根据文档:
DumpRequestOut与DumpRequest类似,但用于传出客户端请求.它包括标准http.Transport添加的所有标头,例如User-Agent.
DumpRequestOut is like DumpRequest but for outgoing client requests. It includes any headers that the standard http.Transport adds, such as User-Agent.
这意味着它将添加"Accept-Encoding:gzip"到印刷的电汇格式.
That means it adds "Accept-Encoding: gzip" to the printed wire format.
要测试实际写入连接的内容,您需要包装 Transport.Dial
或 Transport.DialContext
以提供记录已写入数据的连接.
To test what is actually written to the connection, you need to wrap Transport.Dial
or Transport.DialContext
to provide connection that logs written data.
如果您使用支持 httptrace
的传输器(所有内置和"x/http/..."传输实现均支持),则可以设置WroteHeaderField
回调以检查已编写的标头字段.
If you are using a transport that supports httptrace
(which all built-in and "x/http/..." transport implementation supports), you may set up a WroteHeaderField
callback to inspect written header fields.
但是,如果您只需要检查标题,则可以生成 httptest.Server
.
If you just need to inspect the headers, however, you can spawn up a httptest.Server
.
@EmilePels提供的游乐场链接: https://play.golang.org/p/ZPi-_mfDxI8
Playground link provided by @EmilePels: https://play.golang.org/p/ZPi-_mfDxI8
这篇关于为什么HTTP客户端强制使用Accept-Encoding标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!