在 CentOS 系统下,为 Golang 设置代理可以通过以下几种方法:
在终端中,设置以下环境变量:
export http_proxy="http://proxy.example.com:port"
export https_proxy="http://proxy.example.com:port"
将 proxy.example.com 和 port 替换为你的代理服务器地址和端口。这样,Golang 将使用指定的代理服务器进行网络请求。
注意:这种方法只会在当前的终端会话中生效。如果你关闭终端或打开一个新的终端,你需要重新设置环境变量。
在你的 Golang 代码中,可以使用 http.Transport 结构体和 http.Client 结构体来设置代理。以下是一个示例:
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
proxyURL, err := url.Parse("http://proxy.example.com:port")
if err != nil {
log.Fatal(err)
}
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}
client := &http.Client{
Transport: transport,
Timeout: time.Second * 10,
}
resp, err := client.Get("http://example.com")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}
将 proxy.example.com 和 port 替换为你的代理服务器地址和端口。这段代码将使用指定的代理服务器发送 HTTP 请求。
在 ~/.bashrc 或 ~/.bash_profile 文件中添加以下内容:
export ALL_PROXY="http://proxy.example.com:port"
将 proxy.example.com 和 port 替换为你的代理服务器地址和端口。保存文件并运行 source ~/.bashrc 或 source ~/.bash_profile 使更改生效。
这种方法将在所有终端会话中生效,Golang 将使用指定的代理服务器进行网络请求。