在 CentOS 上配置 Go 的网络环境,通常包含三部分:系统网络与防火墙、Go 模块与程序联网、以及用 Go 编写网络程序时的监听与客户端示例。下面按场景给出可直接执行的步骤与示例。
nmcli con showsudo nmcli con mod "ens160" ipv4.addresses 192.168.125.137/24sudo nmcli con mod "ens160" ipv4.gateway 192.168.125.2sudo nmcli con mod "ens160" ipv4.dns "8.8.8.8 8.8.4.4"sudo nmcli con mod "ens160" ipv4.method manualsudo nmcli con down "ens160" && sudo nmcli con up "ens160"ip addr show ens160 或 ifconfig ens160(若提示无 ifconfig,安装:sudo dnf install net-tools)sudo vi /etc/sysconfig/network-scripts/ifcfg-ens33BOOTPROTO=staticONBOOT=yesIPADDR=192.168.103.203NETMASK=255.255.255.0GATEWAY=192.168.103.1DNS1=8.8.8.8DNS2=8.8.4.4sudo systemctl restart networksudo firewall-cmd --permanent --zone=public --add-service=http && sudo firewall-cmd --permanent --zone=public --add-service=https && sudo firewall-cmd --reloadsudo firewall-cmd --permanent --zone=public --add-port=8080/tcp && sudo firewall-cmd --reloadDNS1/DNS2,或在 /etc/resolv.conf 添加:
nameserver 8.8.8.8search example.comexport GOPROXY=https://goproxy.cn,directexport GOPROXY=https://goproxy.cn,direct 写入 ~/.bashrc 或 /etc/profile 并执行 source ~/.bashrcexport HTTP_PROXY=http://proxy.example.com:8080export HTTPS_PROXY=https://proxy.example.com:8080go get -u github.com/golang/example/hellopackage mainimport ("fmt"; "net/http")func main() { resp, err := http.Get("https://www.google.com"); if err != nil { fmt.Println("Error:", err); return }; defer resp.Body.Close(); fmt.Println("Status:", resp.Status) }go run test_network.golistener, err := net.Listen("tcp", ":8080")for { conn, err := listener.Accept(); go handle(conn) }conn, err := net.Dial("tcp", "127.0.0.1:8080")http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello")) })http.ListenAndServe(":8080", nil)go run server.gocurl http://localhost:8080 或使用上面的 TCP 客户端连接 8080 端口firewall-cmd --list-ports 与云安全组规则,放行对应端口(如 80/443/8080)。sudo setenforce 0;若恢复,请改为调整 SELinux 策略而非长期关闭(生产不建议关闭)。/etc/resolv.conf 中设置可靠 DNS(如 8.8.8.8/1.1.1.1),并验证 /etc/nsswitch.conf 中 hosts 顺序。ip link 或 nmcli con show 确认实际网卡名(如 ens160/ens33),避免配置到错误接口。