ホームページ  >  記事  >  バックエンド開発  >  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 を送信する http.Client の Do メソッドを使用できます。リクエストを実行し、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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。