适用于公司内网请求外网网站,所以需要通过代理转发出去,这里配置一下环境变量COMPANY_HTTP_PROXY、COMPANY_HTTPS_PROXY,通过指定ip请求外网。
// envOnce looks up an environment variable (optionally by multiple
// names) once. It mitigates expensive lookups on some platforms
// (e.g. Windows).
type envOnce struct {
names []string
once sync.Once
val string
}
func (e *envOnce) Get() string {
e.once.Do(e.init)
return e.val
}
func (e *envOnce) init() {
for _, n := range e.names {
e.val = os.Getenv(n)
if e.val != "" {
return
}
}
}
// reset is used by tests
func (e *envOnce) reset() {
e.once = sync.Once{}
e.val = ""
}
var (
httpProxyEnv = &envOnce{
names: []string{"COMPANY_HTTP_PROXY", "company_http_proxy"},
}
httpsProxyEnv = &envOnce{
names: []string{"COMPANY_HTTPS_PROXY", "company_https_proxy"},
}
)
func CompanyProxyFromEnvironment(req *http.Request) (*url.URL, error) {
var proxy string
if req.URL.Scheme == "https" {
proxy = httpsProxyEnv.Get()
}
if proxy == "" {
proxy = httpProxyEnv.Get()
if proxy != "" && os.Getenv("REQUEST_METHOD") != "" {
return nil, errors.New("net/http: refusing to use HTTP_PROXY value in CGI environment; see golang.org/s/cgihttpproxy")
}
}
if proxy == "" {
return nil, nil
}
/*默认使用代理
if !useProxy(canonicalAddr(req.URL)) {
return nil, nil
}*/
proxyURL, err := url.Parse(proxy)
if err != nil || !strings.HasPrefix(proxyURL.Scheme, "http") {
// proxy was bogus. Try prepending "http://" to it and
// see if that parses correctly. If not, we fall
// through and complain about the original one.
if proxyURL, err := url.Parse("http://" + proxy); err == nil {
return proxyURL, nil
}
}
if err != nil {
return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err)
}
return proxyURL, nil
}
有疑问加站长微信联系(非本文作者)