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

Susan Sarandon
Release: 2024-10-26 05:24:30
Original
667 people have browsed it

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>
    Copy after login
  2. Set the proxy URL using ProxyFromEnvironment:

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

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

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

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!