示例代码:package mainimport ( "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.1Host: google.comUser-Agent: Go-http-client/1.1Accept-Encoding: gzip只有req.Header.Set("Accept-Encoding", "*"未注释:GET / HTTP/1.1Host: google.comUser-Agent: Go-http-client/1.1Accept-Encoding: *只有req.Header.Del("Accept-Encoding")未注释:GET / HTTP/1.1Host: google.comUser-Agent: Go-http-client/1.1Accept-Encoding: gzip两行均未注释:GET / HTTP/1.1Host: google.comUser-Agent: Go-http-client/1.1Accept-Encoding: gzipDisableCompression实际上对 HTTP 请求本身有什么作用吗?根据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.
1 回答
繁花如伊
TA贡献2012条经验 获得超12个赞
根据文件:
DumpRequestOut 类似于 DumpRequest,但用于传出客户端请求。它包括标准 http.Transport 添加的任何标头,例如 User-Agent。
这意味着它将“Accept-Encoding: gzip”添加到印刷线路格式中。
要测试实际写入连接的内容,您需要包装Transport.Dial
或Transport.DialContext
提供记录写入数据的连接。
如果您使用支持的传输httptrace
(所有内置和“x/http/...”传输实现都支持),您可以设置WroteHeaderField
回调来检查写入的标头字段。
但是,如果您只需要检查标头,则可以生成一个httptest.Server
.
@EmilePels 提供的游乐场链接:https: //play.golang.org/p/ZPi-_mfDxI8
- 1 回答
- 0 关注
- 142 浏览
添加回答
举报
0/150
提交
取消