如何让Go Workspace优先加载本地模块依赖而非远程下载?
Go工作区本地依赖解析问题
我有一个包含多个Go模块的Go Workspace项目,其中hello模块依赖同一工作区内example/hello目录下的模块,希望依赖能从本地解析而非从互联网下载。
项目结构如下:
example - go.mod - hello - go.mod hello - go.mod go.work
go.work内容为:
go 1.19 use ( ./example/hello ./hello )
example/hello下的go.mod内容是:
module github.com/example/hello go 1.19
当我在hello目录下执行go get github.com/example/hello时,出现如下错误:
go: module github.com/example/hello: git ls-remote -q origin in /Users/joey/go/pkg/mod/cache/vcs/85c69767672480b072ae4eaec76fbf39ef710d025b14e923dd131ac218c9034c: exit status 128: 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.
看起来Go仍尝试从github.com下载依赖而非读取本地工作区,请问是否有办法强制Go优先查找本地目录?
解决方法
1. 添加本地依赖替换指令
在hello目录的go.mod文件中添加replace规则,将目标模块指向本地路径:
replace github.com/example/hello => ../example/hello
执行go mod tidy后,Go会直接使用本地的example/hello模块,不再尝试远程拉取。
2. 在工作区根目录执行命令
Go工作区模式的解析逻辑需要在go.work所在的根目录触发。回到项目根目录,执行:
go get github.com/example/hello
此时Go会识别工作区内已声明的模块,优先使用本地版本。
3. 无需额外go get操作
如果已经通过replace或工作区配置好本地依赖,直接在代码中导入github.com/example/hello即可,Go会自动从本地解析,不需要执行go get。
内容的提问来源于stack exchange,提问作者Joey Yi Zhao
相关产品推荐
相关产品推荐

