CentOS上配置Golang网络需关注环境变量、防火墙、代理等设置,以下是关键操作:
-
环境变量配置
- 设置HTTP/HTTPS代理:
export HTTP_PROXY=http://proxy.example.com:port export HTTPS_PROXY=https://proxy.example.com:port永久生效需添加到
~/.bashrc并执行source ~/.bashrc。 - 配置Go模块代理(GOPROXY):
export GOPROXY=https://goproxy.cn,direct # 国内推荐代理永久生效同上。
- 设置HTTP/HTTPS代理:
-
系统网络配置
- 修改网络接口文件(如
/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
- 开放HTTP/HTTPS端口:
sudo firewall-cmd --permanent --add-service=http sudo firewall-cmd --permanent --add-service=https sudo firewall-cmd --reload ```。 - 若启用SELinux,需允许Go程序访问网络:
sudo setsebool -P httpd_can_network_connect 1 ```。
- 开放HTTP/HTTPS端口:
-
代码级网络参数
- 使用
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环境代理配置:
go env GOPROXY。
- 测试网络连通性:
注意:根据实际需求选择配置方式,代理设置优先通过环境变量或代码实现,系统级配置需谨慎操作。若遇复杂网络问题,可结合tcpdump等工具抓包分析。