示例代碼: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 關注
- 167 瀏覽
添加回答
舉報
0/150
提交
取消