Go依赖管理必不可少的文件-go.mod

1如何管理依赖

  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

  1. 在你的代码中启动依赖追踪

    为了追踪和管理你代码中要添加的依赖,你要把自己的代码放入到自己定义的模块中=>创建go.mod文件

    go mod init <module-path>
    //If possible, the module path should be the repository location of your source code
    
    1. 命名模块module path:首先确保的module path与其他模块没有冲突

      格式:/
      在这里插入图片描述

  2. 同步你的代码的依赖关系

    go mod tidy -v
    //-v是打印被删除的模块
    

    目的:保持你的代码依赖的完整性和整洁性,go mod tidy会自动修改go.mod文件添加并下载你需要的依赖但是还没下载到本地的,删除你不需要的依赖

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JOz2MRC2-1654824102111)(Managing dependencies.assets/image-20220607112147986-16545721092613.png)]
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重定向至已经发布的模块
//但是重定向至已发布的模块必须要指明指向哪个版本即@版本号
  1. 把下载的依赖包放到项目內部,而不是放在$GOPATH/pkg/mod的module-cache中

    The go mod vendor command constructs a directory named vendor 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作用:

    1. 创建名为vendor的文件夹
    2. 将该module的所有依赖包都放置在该vendor文件夹中
    3. 在该vendor文件夹中创建modules.txt文件,表明vendor文件夹中包名+版本号
2go.mod文件参考
  1. go.mod文件的组成:
    [外链图片转存失败,源站可能有防盗链机
制,建议将图片保存下来失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UUGfLsPQ-1654824102116)(Managing dependencies.assets/image-20220607113856469-16545731372995.png)(Managing dependencies.assets/image-20220607113856469-16545731372995.png)]
  1. module path:Go tools可以下载该module的路径(如果该模块还没发布必须要用go mod edit -replace将模块路径重定向至本地的模块路径使得可以使用该模块)
  2. go:该模块使用的最低版本的Go
  3. module requires:该模块使用其他最低版本的模块列表
  4. [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AM38AI80-1654824102117)(Managing dependencies.assets/image-20220607114827997.png)]

对于Module部分:

  1. 语法:module
    在这里插入图片描述
  2. 例子:
    在这里插入图片描述
深入了解Go Module机制
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Blockchain410

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值