Home  >  Article  >  Backend Development  >  How to Set Headers for HTTP Requests Using `http.Client` and `http.Transport` in Go?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 04:30:02146browse

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

Setting Headers for Requests Using http.Client and http.Transport

To set headers for HTTP requests, one can use http.Client's Do method, which sends an HTTP request and returns an http.Response. Before sending the request, headers can be modified using the Header field of the *http.Request object.

In your case, with a custom setup of http.Transport and http.Dialer to specify the IP address, headers can be set as follows:

<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>

The above is the detailed content of How to Set Headers for HTTP Requests Using `http.Client` and `http.Transport` in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn