1如何管理依赖
-
以模块为单位管理依赖
Go code is grouped into packages, and packages are grouped into modules.
Go源代码=>Go 包(Package)=>Go 模块(Module)
在Go中,你可以以模块为单位管理你需要import的依赖。
3. 定位和导入有用的包
其中rsc.io/quote是module path
-
在你的代码中启动依赖追踪
为了追踪和管理你代码中要添加的依赖,你要把自己的代码放入到自己定义的模块中=>创建go.mod文件
go mod init <module-path> //If possible, the module path should be the repository location of your source code
-
命名模块module path:首先确保的module path与其他模块没有冲突
格式:/
-
-
同步你的代码的依赖关系
go mod tidy -v //-v是打印被删除的模块
目的:保持你的代码依赖的完整性和整洁性,go mod tidy会自动修改go.mod文件添加并下载你需要的依赖但是还没下载到本地的,删除你不需要的依赖
6. 开发和测试未发布的模块代码
场景:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eO3p5PUL-1654824102112)(Managing dependencies.assets/image-20220607112454034-16545722950134.png)]
go mod edit -replace=example.com/theirmodule@v0.0.0-unpublished=../theirmodule
//把example.com/theirmodule@v0.0.0-unpublished重定向至../theirmodule模块
//或者你可以把example.com/theirmodule@v0.0.0-unpublished重定向至已经发布的模块
//但是重定向至已发布的模块必须要指明指向哪个版本即@版本号
-
把下载的依赖包放到项目內部,而不是放在$GOPATH/pkg/mod的module-cache中
The
go mod vendor
command constructs a directory namedvendor
in the main module’s root directory containing copies of all packages needed to build and test packages in the main module.go mod vendor//在module-path的根目录下创建一个vendor文件夹,并且依赖包下载至vendor下
go mod vendor作用:
- 创建名为vendor的文件夹
- 将该module的所有依赖包都放置在该vendor文件夹中
- 在该vendor文件夹中创建modules.txt文件,表明vendor文件夹中包名+版本号
2go.mod文件参考
- go.mod文件的组成:
- module path:Go tools可以下载该module的路径(如果该模块还没发布必须要用go mod edit -replace将模块路径重定向至本地的模块路径使得可以使用该模块)
- go:该模块使用的最低版本的Go
- module requires:该模块使用其他最低版本的模块列表
对于Module部分:
- 语法:module
- 例子: