• 周六. 7 月 27th, 2024

    go get github.com/xxx private repository error

    root

    4 月 15, 2022 #go get, #private repository

    直接使用go get ...添加私有仓库依赖时,会出现以下错误:

    go get: module github.com/unknown/com: git ls-remote -q origin in D:\IDEA\go\pkg\mod\cache\vcs\ca60e3dfa1619897170f0f21e6f875c057be28088185a4024963a17a2db23167: exit status 128:
            Logon failed, use ctrl+c to cancel basic credential prompt.
            fatal: could not read Username for 'https://github.com': terminal prompts disabled
    Confirm the import path was entered correctly.
    If this is a private repository, see https://golang.org/doc/faq#git_https for additional information.
    

    从错误信息可以明显地看出来,我们使用私有仓库时通常会配置ssh-pubkey进行鉴权,但是go get使用https而非ssh的方式来下载依赖,从而导致鉴权失败。

    如果配置了GOPROXY代理,错误信息则是如下样式:

    go get gitlab.com/xxx: module gitlab.com/xxx: reading https://goproxy.io/gitlab.com/xxx/@v/list: 404 Not Found

    从错误信息可以看出,go get通过代理服务拉取私有仓库,而代理服务当然不可能访问到私有仓库,从而出现了404错误。

    1.111.12版本中,比较主流的解决方案是配置git强制采用ssh

    这个解决方案在许多博客、问答中都可以看到:

    git config –global url.”git@gitlab.com:xxx/zz.git”.insteadof “https://gitlab.com/xxx/zz.git”

    但是它与GOPROXY存在冲突,也就是说,在使用代理时,这个解决方案也是不生效的。

    1.13版本之后,前面介绍的解决方案又会导致go get出现另一种错误:

    get “gitlab.com/xxx/zz”: found meta tag get.metaImport{Prefix:”gitlab.com/xxx/zz”, VCS:”git”, RepoRoot:”https://gitlab.com/xxx/zz.git”} at //gitlab.com/xxx/zz?go-get=1
    verifying gitlab.com/xxx/zz@v0.0.1: gitlab.com/xxx/zz@v0.0.1: reading https://sum.golang.org/lookup/gitlab.com/xxx/zz@v0.0.1: 410 Gone

    这个错误是因为新版本go mod会对依赖包进行checksum校验,但是私有仓库对sum.golang.org是不可见的,它当然没有办法成功执行checksum

    也就是说强制git采用ssh的解决办法在1.13版本之后GG了。

    当然Golang在堵上窗户之前,也开了大门,它提供了一个更方便的解决方案:GOPRIVATE环境变量。解决以上的错误,可以这样配置:

    export GOPRIVATE=gitlab.com/xxx

    它可以声明指定域名为私有仓库,go get在处理该域名下的所有依赖时,会直接跳过GOPROXYCHECKSUM等逻辑,从而规避掉前文遇到的所有问题。

    另外域名gitlab.com/xxx非常灵活,它默认是前缀匹配的,所有的gitlab.com/xxx前缀的依赖模块都会被视为private-modules,它对于企业、私有Group等有着一劳永逸的益处。

    提示:如果你通过ssh公钥访问私有仓库,记得配置git拉取私有仓库时使用ssh而非https

    可以通过命令git config ...的方式来配置。也可以像我这样,直接修改~/.gitconfig添加如下配置:

    [url “git@github.com:”]
    insteadOf = https://github.com/
    [url “git@gitlab.com:”]
    insteadOf = https://gitlab.com/

    即可强制go get针对github.comgitlab.com使用ssh而非https

    root