golang下如何replace替换第三方库

500阅读 0评论2024-04-19 jiuniu110
分类:其他平台

问题:
在开发过程中,经常遇到golang依赖的第三方托管在github上,如:github.com/foo/third_lib
而如上库因为各种原有,需要fork 修改后 提交到本地内网私有git 仓库中。

此时,可通过在 go.mod中增加 replace指令进行替换。

三种方式

1. 直接替换为内部私有仓库的的地址,并指定tag
  1. replace github.com/foo/third_lib => mygit.com/foo/third_lib v1.2.3

2. 指定本地内网仓库 及 依赖的tag-提交日期-commit记录,
   此处v0.0.0是伪版本(pseudo-version),用于在项目中当前commit记录无tag的情况下,理解为占位符。
  1. replace github.com/foo/third_lib => mygit.com/foo/third_lib v0.0.0-20230418161637-381874068884

3. 直接指定本地目录, 此处假设已经将
mygit.com/foo/third_lib clone 至当前项目的同一级目录
  1. replace github.com/foo/third_lib => ../third_lib


以上,优选 第1/2方式,可以自动化构建,且1方式因为有tag更好管理。
此外
如果内部的私有git 配置了禁止通过git clone  https 或 http访问,可以通过 配置~/.gitconfig进一步解决
此处为:
# cat ~/.gitconfig 
  1. [url "ssh://git@mygit.com/"]
  2.         insteadOf = https://mygit.com/
  3. [url "ssh://git@mygit.com/"]
  4.         insteadOf = http://mygit.com/

修改完毕后,在执行go mod tidy 对仓库进行更新。

如果执行完毕提示如下错误,

go mod tidy
verifying module: mygit.com/foo/third_lib@v0.0.0-20230418161637-381874068884: reading : reading mygit.com/foo/third_lib@v0.0.0-20230418161637-381874068884 404 Not Found

执行export GOPRIVATE=mygit.com

更多,可参考:
https://pkg.go.dev/cmd/go#hdr-Configuration_for_downloading_non_public_code



上一篇:javascript中函数的入参缺少类型自动补齐
下一篇:git 本地分支与远程分支冲突解决办法