>  기사  >  백엔드 개발  >  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 객체의 헤더 필드를 사용하여 헤더를 수정할 수 있습니다.

귀하의 경우 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으로 문의하세요.