温馨提示×

golang在linux怎样配私库

小樊
38
2026-10-18 20:21:20
栏目: 编程语言

在 Linux 下配置 Go 私有仓库(私库),通常分几种场景:

  • 公司内网 Git(GitLab / Gitea / 自建 Git)
  • 私有 Go Module(不直接公开到 proxy.golang.org)
  • 需要账号密码 / Token 鉴权

下面按最常见、最推荐的方式讲。


一、基础环境准备

1. Go 版本要求

建议使用 Go 1.13+(私库支持更完善)

go version

2. 开启 Go Module

go env -w GO111MODULE=on

二、配置私有仓库(最关键)

假设你的私库地址是:

git.company.com/mygroup/myproject

1. 告诉 Go 这是私有库(不会走公共 proxy)

go env -w GOPRIVATE="git.company.com/*"

✅ 效果:

  • 不走 proxy.golang.org
  • 不走 sum.golang.org
  • 直接使用 git 拉取

如果有多个:

go env -w GOPRIVATE="git.company.com/*,github.com/yourorg/*"

三、Git 鉴权配置(非常重要)

Go 拉私库本质是 git clone

方式一:SSH(最推荐)

1. 生成 SSH key

ssh-keygen -t ed25519 -C "you@company.com"

2. 把公钥加到 Git 服务器

  • GitLab / Gitea / GitHub → SSH Keys

3. 配置 ~/.gitconfig

[url "git@git.company.com:"]
    insteadOf = https://git.company.com/

这样 Go 会自动用 SSH 拉代码。


方式二:HTTPS + Token(常用)

1. 配置 Git Credential

git config --global credential.helper store

2. 第一次拉取时输入

用户名
Token(不是密码)

3. 或写死在 URL(不推荐生产)

go env -w GOPRIVATE="git.company.com/*"
git config --global url."https://username:token@git.company.com/".insteadOf "https://git.company.com/"

四、Go 代理(可选但推荐)

保留公共代理,仅私库绕过

go env -w GOPROXY="https://proxy.golang.org,direct"
go env -w GONOPROXY="git.company.com/*"

五、使用示例

1. 在代码中引用

import "git.company.com/mygroup/myproject"

2. 拉取

go mod tidy

六、常见问题排查

1. 403 / 401

  • SSH key 未配置
  • Token 权限不足
  • GOPRIVATE 没配

2. unknown revision

go env -w GOFLAGS=-mod=mod

3. 仍在走 proxy

go env | grep GOPRIVATE

七、典型企业方案(推荐)

场景 方案
内网 Git SSH + GOPRIVATE
云私库 HTTPS Token
多仓库 GOPRIVATE 通配
高安全 GONOSUMDB

如果你愿意,可以告诉我:

  • 你用的是 GitLab / Gitea / GitHub / 其他
  • 是 SSH 还是 HTTPS
  • Go 版本

我可以给你一套 可直接复制的配置文件。

0 踩