在CentOS上配置Golang的代理,可以通过设置环境变量来实现。以下是详细的步骤:
如果你需要通过HTTP代理访问互联网,可以设置HTTP_PROXY
和HTTPS_PROXY
环境变量。
export HTTP_PROXY=http://your.proxy.server:port
export HTTPS_PROXY=https://your.proxy.server:port
编辑你的shell配置文件(例如.bashrc
或.bash_profile
),添加以下行:
export HTTP_PROXY=http://your.proxy.server:port
export HTTPS_PROXY=https://your.proxy.server:port
然后使更改生效:
source ~/.bashrc # 或者 source ~/.bash_profile
如果你有一些内部域名不需要通过代理访问,可以设置NO_PROXY
环境变量。
export NO_PROXY=localhost,127.0.0.1,.example.com
编辑你的shell配置文件,添加以下行:
export NO_PROXY=localhost,127.0.0.1,.example.com
然后使更改生效:
source ~/.bashrc # 或者 source ~/.bash_profile
你可以通过运行一个简单的Go程序来验证代理设置是否正确。
创建一个名为main.go
的文件,内容如下:
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
resp, err := http.Get("http://httpbin.org/ip")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
fmt.Println("Your IP is:", resp.Header.Get("X-Forwarded-For"))
}
运行程序:
go run main.go
如果代理设置正确,你应该会看到通过代理服务器访问的IP地址。
go env
命令查看当前环境变量你可以使用go env
命令查看当前的Go环境变量,包括代理设置:
go env
通过设置HTTP_PROXY
、HTTPS_PROXY
和NO_PROXY
环境变量,你可以在CentOS上轻松配置Golang的代理。确保这些设置在你的shell配置文件中持久化,以便每次启动终端时都能自动应用这些设置。