首頁  >  文章  >  後端開發  >  如何在 Go 中使用 `http.Client` 和 `http.Transport` 設定 HTTP 請求標頭?

如何在 Go 中使用 `http.Client` 和 `http.Transport` 設定 HTTP 請求標頭?

Patricia Arquette
Patricia Arquette原創
2024-10-25 04:30:02146瀏覽

How to Set Headers for HTTP Requests Using `http.Client` and `http.Transport` in Go?

使用http.Client 和http.Transport 設定請求頭

要設定HTTP 請求的頭,可以使用http.Client 的Do 方法,該方法發送一個HTTP請求並返回http.Response。在傳送請求之前,可以使用 *http.Request 物件的 Header 欄位修改標頭。

在您的情況下,使用 http.Transport 和 http.Dialer 的自訂設定來指定 IP 位址、標頭可以設定如下:

<code class="go">// Create a new HTTP client with the custom transport
client := &http.Client{
    Transport: &http.Transport{
        // ...
    },
}

// Create a new HTTP request
req, err := http.NewRequest("GET", "https://www.whatismyip.com/", nil)
if err != nil {
    // handle error
}

// Set the headers
req.Header.Set("name", "value")

// Send the request and handle the response
resp, err := client.Do(req)
if err != nil {
    // handle error
}

// Read and print the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    // handle error
}
fmt.Println(string(body))</code>

以上是如何在 Go 中使用 `http.Client` 和 `http.Transport` 設定 HTTP 請求標頭?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn