首頁 > 後端開發 > Golang > 主體

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

Patricia Arquette
發布: 2024-10-25 04:30:02
原創
156 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!