適用于公司內(nèi)網(wǎng)請求外網(wǎng)網(wǎng)站,所以需要通過代理轉(zhuǎn)發(fā)出去,這里配置一下環(huán)境變量COMPANY_HTTP_PROXY辩块、COMPANY_HTTPS_PROXY,通過指定ip請求外網(wǎng)荆永。
// 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
}
/*默認(rèn)使用代理
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
}