2 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以使用http.ProxyFromEnvironment方法
var PTransport = & http.Transport { Proxy: http.ProxyFromEnvironment }
client: = http.Client { Transport: PTransport }
ProxyFromEnvironment 返回用于給定請(qǐng)求的代理的 URL,如環(huán)境變量 HTTP_PROXY、HTTPS_PROXY 和 NO_PROXY(或其小寫版本)所示。對(duì)于 https 請(qǐng)求,HTTPS_PROXY 優(yōu)先于 HTTP_PROXY。
我試過(guò)下面的代碼,它有效,只需在終端中添加你的代理詳細(xì)信息。
export http_proxy='http://user:password@prox-server:3128'
export https_proxy='http://user:password@prox-server:3128'
export HTTP_PROXY='http://user:password@prox-server:3128'
export HTTPS_PROXY='http://user:password@prox-server:3128'
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
var PTransport = & http.Transport {
Proxy: http.ProxyFromEnvironment
}
client: = http.Client {
Transport: PTransport
}
req, err: = http.NewRequest("GET", "https://jsonplaceholder.typicode.com/todos/1", nil)
req.Header.Add("If-None-Match", `some value`)
resp, err: = client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyBytes, err: = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
bodyString: = string(bodyBytes)
fmt.Printf("GET Response = %s \n", string(bodyString))
}

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超5個(gè)贊
將傳輸代理字段設(shè)置為http.ProxyFromEnvironment以使用從環(huán)境變量配置的代理:
tr := &http.Transport{ Proxy: ProxyFromEnvironment, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }
通常最好克隆默認(rèn)傳輸并在該傳輸中設(shè)置您的選項(xiàng):
tr := http.DefaultTransport.(*http.Transport).Clone() tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} client := &http.Client{Transport: tr} resp, err := client.Get(url)
默認(rèn)傳輸包括代理字段、超時(shí)和其他有用設(shè)置的正確值。
如果應(yīng)用程序沒(méi)有創(chuàng)建自定義傳輸,則不需要這些來(lái)支持與代理相關(guān)的環(huán)境變量。
- 2 回答
- 0 關(guān)注
- 125 瀏覽
添加回答
舉報(bào)