Home >Backend Development >Golang >How to Use a Proxy with a Custom Transport in Go?

How to Use a Proxy with a Custom Transport in Go?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 05:24:30751browse

How to Use a Proxy with a Custom Transport in Go?

Program Go for Proxy Usage with Custom Transport

In Go, you can configure the standard library's http.Client to automatically use a proxy based on environment variables. However, when using a custom transport, this functionality is not directly supported.

The solution is to utilize the http.ProxyFromEnvironment method. This method returns the proxy URL to use for a given request based on environment variables such as HTTP_PROXY and HTTPS_PROXY.

To use a proxy with a custom transport in Go, follow these steps:

  1. Create a custom http.Transport instance:

    <code class="go">tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }</code>
  2. Set the proxy URL using ProxyFromEnvironment:

    <code class="go">var PTransport = &http.Transport{Proxy: http.ProxyFromEnvironment}</code>
  3. Create a http.Client with the custom transport:

    <code class="go">client := http.Client{Transport: PTransport}</code>
  4. Use the client to make requests:

    <code class="go">resp, err := client.Get(url)</code>

Here's a code example demonstrating this approach:

<code class="go">package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    var PTransport = &http.Transport{Proxy: http.ProxyFromEnvironment}

    client := http.Client{Transport: PTransport}
    resp, err := client.Get("https://jsonplaceholder.typicode.com/todos/1")
    if err != nil {
        panic(err)
    }

    bodyBytes, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    fmt.Printf("GET Response = %s \n", string(bodyBytes))
}</code>

Remember to set the HTTP_PROXY and HTTPS_PROXY environment variables appropriately for your proxy server.

The above is the detailed content of How to Use a Proxy with a Custom 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