Home >Backend Development >Golang >How to Configure a Proxy for HTTP Clients in Go?

How to Configure a Proxy for HTTP Clients in Go?

DDD
DDDOriginal
2024-12-18 21:44:16605browse

How to Configure a Proxy for HTTP Clients in Go?

Configuring Proxy for HTTP Client in Go

When working with HTTP clients, it's often necessary to set up a proxy to manage network traffic. However, navigating the documentation can be confusing, as specific proxy-related functions may not be readily apparent.

HTTP_PROXY Environment Variable

One straightforward approach is to set the HTTP_PROXY environment variable. This will instruct Go to use the specified proxy by default:

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

Custom HTTP Client

Alternatively, you can create a custom http.Client that explicitly uses a proxy:

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

This method is useful when you cannot rely on environment configuration or prefer not to modify it.

Default Transport Modification

Lastly, you can modify the default transport used by the net/http package, affecting all HTTP clients in your program:

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

The above is the detailed content of How to Configure a Proxy for HTTP Clients 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