Home >Backend Development >Golang >How to Configure Proxies for Go's HTTP Client?

How to Configure Proxies for Go's HTTP Client?

Susan Sarandon
Susan SarandonOriginal
2025-01-03 17:26:39391browse

How to Configure Proxies for Go's HTTP Client?

Proxy Configuration for Go HTTP Client

Many HTTP client applications require the use of a proxy to access websites or services. Go provides flexibility in setting up proxy configurations for its HTTP client.

Default Proxy Configuration

To use a proxy automatically, you can set the following environment variable:

export HTTP_PROXY="http://proxyIp:proxyPort"

Alternatively, you can use the os package in Go:

os.Setenv("HTTP_PROXY", "http://proxyIp:proxyPort")

Custom Proxy Configuration

If you need more granular control over proxy configuration, you can create a custom HTTP client that explicitly uses a proxy:

proxyUrl, _ := url.Parse("http://proxyIp:proxyPort")
myClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}}

You can use this custom client to make requests:

resp, err := myClient.Get("http://example.com")

Modifying Default Transport

Another option is to modify the default transport used by the net/http package:

proxyUrl, _ := url.Parse("http://proxyIp:proxyPort")
http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}

This configuration affects all HTTP requests made by your program, using the default HTTP client or custom clients that do not specify a proxy.

The above is the detailed content of How to Configure Proxies for Go's HTTP Client?. 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