使用环境变量配置Go HTTP代理

在Go语言中,你可以使用 ProxyFromEnvironment 函数根据环境变量轻松地为HTTP请求配置代理。

// ProxyFromEnvironment returns the URL of the proxy to use for a
// given request, as indicated by the environment variables
// HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions
// thereof). Requests use the proxy from the environment variable
// matching their scheme, unless excluded by NO_PROXY.
//
// The environment values may be either a complete URL or a
// 'host[:port]', in which case the 'http' scheme is assumed.
// The schemes 'http', 'https', and 'socks5' are supported.
// An error is returned if the value is a different form.
//
// A nil URL and nil error are returned if no proxy is defined in the
// environment, or a proxy should not be used for the given request,
// as defined by NO_PROXY.
//
// As a special case, if req.URL.Host is 'localhost' (with or without
// a port number), then a nil URL and nil error will be returned.
func ProxyFromEnvironment(req *Request) (*url.URL, error) {
	return envProxyFunc()(req.URL)
}

如何配置

ProxyFromEnvironment 函数根据以下环境变量确定请求使用的代理:

  • HTTP_PROXY: 用于HTTP请求的代理地址。
  • HTTPS_PROXY: 用于HTTPS请求的代理地址。
  • NO_PROXY: 以逗号分隔的主机名列表,不使用代理。

你可以使用完整的URL或 host[:port] 形式设置这些环境变量,默认使用 http scheme。支持的 scheme 包括 httphttpssocks5

示例

设置代理:

export HTTP_PROXY='http://proxy.example.com:8080'
export HTTPS_PROXY='http://proxy.example.com:8080'

设置不使用代理的主机:

export NO_PROXY='localhost,127.0.0.1,.example.com'

特殊情况

  • 如果环境变量中没有定义代理,或者根据 NO_PROXY 的配置不应该使用代理,则返回 nil URL 和 nil 错误。
  • 如果请求的 URL.Hostlocalhost(带或不带端口号),则返回 nil URL 和 nil 错误,表示不使用代理。

通过使用 ProxyFromEnvironment 函数和相关的环境变量,你可以方便地在你的Go应用程序中配置HTTP代理。

Go语言网络编程:使用环境变量配置HTTP代理

原文地址: https://www.cveoy.top/t/topic/fEpV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录