您可以使用 http.ProxyFromEnvironment 方法
var PTransport = & http.Transport { Proxy: http.ProxyFromEnvironment } client: = http.Client { Transport: PTransport }ProxyFromEnvironment返回用于给定请求的代理的URL,如环境变量HTTP_PROXY,HTTPS_PROXY和NO_PROXY(或其小写版本)所指示。对于HTTPS请求,HTTPS_PROXY优先于HTTP_PROXY。
我试过下面的代码,它的工作原理,只需在终端中添加您的代理详细信息。
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 mainimport ( "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.typipre.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))}


