Go

Golang无法下载包问题解决-GOPROXY&GOPRIVAT

2021-09-18  本文已影响0人  Jerry_1116

国内由于GFW和网速比较慢的原因,部分网站无法直接访问。但是golang学习者从部分技术网站下载代码进行学习又是必不可少的。

1 问题描述

作为golang开发者,当执行go getgo installgo mod命令时,会自动下载相应的代码包或者依赖包。
例如,执行go get golang.org/x/net,经常下载失败。

2 问题解决

设置GOPROXY为国内大厂的golang代码镜像代理。go module包依赖管理工具在golang 1.11+支持,并添加了GOPROXY环境变量。
如果设置了GOPROXY环境变量,下载源代码时会通过GOPROXY设置的代理地址下载。
如果Golang的版本golang1.13+,可以设置GOPRIVATE 环境变量来控制直接走本地的私有仓库和依赖(一般是公司内部的golang私有仓库),而无需通过 proxy 来拉取。

3 设置方法

  1. Linux, MacOS
# 启用Go module功能
export GO111MODULE=on
# 配置GOPROXY环境变量 export GOPROXY={proxy_url}
export GOPROXY=https://goproxy.io,direct
# Set environment variable allow bypassing the proxy for specified repos (optional if Go version >=1.13)
export GOPRIVATE=git.mycompany.com,github.com/my/private

或者:

$ echo "export GO111MODULE=on" >> ~/.profile
$ echo "export GOPROXY=https://goproxy.cn" >> ~/.profile
$ source ~/.profile
  1. Windows
    PowerShell中运行以下命令:
# 启用go module功能
$env:GO111MODULE="on"
# 配置GOPROXY环境变量$env:GOPROXY="{proxy_url}"
$env:GOPROXY = "https://goproxy.io,direct"
# Set environment variable allow bypassing the proxy for specified repos (optional if Go version >=1.13)
$env:GOPRIVATE = "git.mycompany.com,github.com/my/private"

4 可用的代理

  1. GOPROXY.IO - A Global Proxy for Go Modules
# Set the GOPROXY environment variable
export GOPROXY=https://goproxy.io,direct
# Set environment variable allow bypassing the proxy for specified repos (optional if Go version >=1.13)
export GOPRIVATE=git.mycompany.com,github.com/my/private
# Set the GOPROXY environment variable
$env:GOPROXY = "https://goproxy.io,direct"
# Set environment variable allow bypassing the proxy for specified repos (optional if Go version >=1.13)
$env:GOPRIVATE = "git.mycompany.com,github.com/my/private"
  1. Goproxy.cn - 七牛云
    设置方法见3 设置方法
    GOPROXY的URL为:https://goproxy.cn

  2. 阿里云Go Module代理服务
    设置方法见3 设置方法
    GOPROXY的URL为:https://mirrors.aliyun.com/goproxy/

4 参考

  1. GOPROXY:解决 go get golang.org/x 包失败
  2. Managing dependencies - The Go Programming Language
上一篇下一篇

猜你喜欢

热点阅读