
php小编百草为你介绍如何使用go工作区在本地加载依赖项。在开发Go语言项目时,我们经常会使用到各种第三方库和依赖项。为了方便管理和加载这些依赖项,Go语言提供了一个强大的工作区(workspace)机制。通过设置工作区路径和使用go mod命令,我们可以快速、方便地加载和管理项目所需的依赖项,提高开发效率和代码质量。下面我们就来详细了解一下如何使用go工作区在本地加载依赖项。
我有一个 go 工作区项目,其中包含一些 go 模块。一个模块依赖于同一工作区中的另一个模块。我希望在本地解决依赖关系,而无需从互联网下载。
我有两个模块,hello 和 example。 hello 依赖于 example。其结构为:
example
- go.mod
- hello
- go.mod
hello
- go.mod
go.workgo.work 是:
go 1.19
use (
./example/hello
./hello
)模块 hello 需要使用从 example -> 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下载依赖项而不是查看本地worksapce。有没有办法强制 go 首先查看本地目录?
完整代码为:https://github.com/zhaoyi0113/go-workspace
go.mod 文件中的模块名称与项目结构相关。否则,随机命名可能会导致与其他库发生冲突,从而导致在构建依赖项时不清楚要拉取哪个库。
换句话说,目录结构必须匹配才能从 GitHub 获取代码。因此,将“example”目录下的go.mod文件中的模块名称更改为:
module github.com/zhaoyi0113/go-workspace/example
对于“hello”目录:
module github.com/zhaoyi0113/go-workspace/hello
如果“hello”目录需要依赖“example”模块,则导入如下:
require (
github.com/zhaoyi0113/go-workspace/example xxxx
)这里,如果您创建了版本,“xxxx”可以是版本号。如果没有,您可以使用推送到 GitHub 的代码中的 Git 提交哈希。您可以在 GitHub 项目页面上找到“example”的 Git 哈希值。在“hello”目录下,执行以下命令:
go get github.com/zhaoyi0113/go-workspace/example@{git version prefix, which can be found on the GitHub project page}但是,这种方法只允许您获取已推送到 GitHub 的代码。如果你想在本地快速调试开发,可以在go.mod文件中添加“replace”指令:
replace github.com/zhaoyi0113/go-workspace/example => {local directory of your example}更新
建议使用包方法组织项目结构,其中模块应该更加独立,并且通常位于不同的存储库中。
. ├── example │ ├── reverse │ └── utils.go ├── hello │ └── hello.go ├── go.mod ├── go.sum └── main.go
以上就是如何使用go工作区在本地加载依赖项?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号