Ubuntu配置Golang网络设置的核心步骤
Go Modules是Golang的依赖管理工具,需先启用才能正常使用代理和依赖管理功能。
执行命令:go env -w GO111MODULE=on
验证是否开启:go env | grep GO111MODULE(输出应为GO111MODULE=on)。
国内用户访问golang.org等官方源常遇网络障碍,需通过GOPROXY环境变量设置代理服务器。
export GOPROXY=https://goproxy.cn,direct(goproxy.cn是国内常用的免费代理,direct表示代理失效时直接连接源站)。~/.bashrc、~/.zshrc),然后运行source ~/.bashrc(或对应配置文件)使更改生效。go env | grep GOPROXY,确认输出包含你设置的代理地址。若系统本身无法访问外网(如无网络连接、DNS解析失败),需先配置Ubuntu的网络。
/etc/netplan/01-netcfg.yaml),添加静态IP或DNS配置(示例为静态IP):network:
version: 2
renderer: networkd
ethernets:
eth0: # 网卡名称(可通过`ip a`命令查看)
dhcp4: no
addresses: [192.168.1.100/24] # 静态IP地址及子网掩码
gateway4: 192.168.1.1 # 网关地址
nameservers:
addresses: [8.8.8.8, 8.8.4.4] # DNS服务器
保存后运行sudo netplan apply应用配置。/etc/network/interfaces):/etc/network/interfaces文件,添加以下内容(静态IP示例):auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
dns-nameservers 8.8.8.8 8.8.4.4
保存后运行sudo systemctl restart networking重启网络服务。若通过go get或Git拉取Go模块,需配置Git的HTTP/HTTPS代理。
git config --global http.proxy http://your.proxy.server:port、git config --global https.proxy http://your.proxy.server:port(替换为你的Git代理地址和端口)。~/.bashrc),然后运行source ~/.bashrc使更改生效。goproxy.cn(七牛云提供)或goproxy.io(官方推荐的国内镜像),速度较快且稳定。ufw),需允许Golang程序访问网络(如sudo ufw allow out 80/tcp、sudo ufw allow out 443/tcp),避免因防火墙阻止导致网络请求失败。