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/[email protected]重定向至../theirmodule模块
//或者你可以把example.com/[email protected]重定向至已经发布的模块
//但是重定向至已发布的模块必须要指明指向哪个版本即@版本号
  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机制

猜你喜欢

转载自blog.csdn.net/Blockchain210/article/details/125215347