CentOS上配置Golang网络需关注环境变量、防火墙、代理等设置,以下是关键操作:
环境变量配置
export HTTP_PROXY=http://proxy.example.com:port
export HTTPS_PROXY=https://proxy.example.com:port
永久生效需添加到~/.bashrc并执行source ~/.bashrc。export GOPROXY=https://goproxy.cn,direct # 国内推荐代理
永久生效同上。系统网络配置
/etc/sysconfig/network-scripts/ifcfg-ensXX):BOOTPROTO=static
IPADDR=192.168.1.100
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=8.8.8.8
ONBOOT=yes
重启网络服务:sudo systemctl restart network。防火墙与SELinux
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
```。
sudo setsebool -P httpd_can_network_connect 1
```。
代码级网络参数
net包设置TCP参数(如KeepAlive):conn, _ := net.Dial("tcp", "example.com:80")
if tcpConn, ok := conn.(*net.TCPConn); ok {
tcpConn.SetKeepAlive(true)
tcpConn.SetKeepAlivePeriod(30 * time.Second)
}
```。
调试与验证
ping example.com或curl -x http://proxy:port example.com。go env GOPROXY。注意:根据实际需求选择配置方式,代理设置优先通过环境变量或代码实现,系统级配置需谨慎操作。若遇复杂网络问题,可结合tcpdump等工具抓包分析。