这是我参与「第五届青训营 」伴学笔记创作活动的第 1 天
一、什么是go module
官方解释(go.dev/ref/mod):
A module is a collection of packages that are released, versioned, and distributed together. Modules may be downloaded directly from version control repositories or from module proxy servers.
A module is identified by a module path, which is declared in a go.modfile, together with information about the module’s dependencies. The module root directory is the directory that contains the go.mod file. The main module is the module containing the directory where the go command is invoked.
module是由一系列一起发布、分发、版本存储的包构成的,每个包都是由go.mod中的module path和这个module的所有依赖一起定义的。含有go.mod文件的目录就是这个module的根目录
二、module path
module path是一个module的规范名称, module path定义在go.mod文件中,一个module path是这个module中所有包的前缀
//go.mod 文件中的第一行, 定义了 module path = "golang.org/x/net"
module golang.org/x/net
三、 packge path
packge path就是包含该packge的子目录 加上module path,例如:"golang.org/x/net/html"就是module "golang.org/x/net"中 html子目录的 packge path, 同时也是这个包的导入路径
四、go directive
1、require directive
require表明对于所依赖的模块的最低版本号
require module后的//indirect的注释表明 主moudule没有直接引入(import 中声明的)该module中的任意packge
require golang.org/x/net v1.2.3
require (
golang.org/x/crypto v1.4.5 // indirect // 表明主模块没有直接引入该module中的任意packge
golang.org/x/text v1.6.7
)
2. replace directive
将一个module的某个版本替换为另一个module 或者这个module的任意版本都将被替换为另一个module
箭头右端的module如果以 ./ 或 ../ 开头将解析为它将被解释为替换模块根目录的本地文件路径,此时该路径下需要有一个go.mod文件,此时版本号可以省略
如果箭头右端的path不是本地的,则此时需要指定一个版本号,并且是一个合法的module路径
replace golang.org/x/net v1.2.3 => example.com/fork/net v1.4.5
replace (
golang.org/x/net v1.2.3 => example.com/fork/net v1.4.5 //指定版本时,只替换特定版本
golang.org/x/net => example.com/fork/net v1.4.5 // 该module的任意版本都会被替换
golang.org/x/net v1.2.3 => ./fork/net // 指定版本替换为本地的module, 此时右端不需要指定版本号
golang.org/x/net => ./fork/net
)
五、常用命令
1. go mod init
初始化当前文件夹,创建 go.mod 文件
2. go tidy
增加缺少的包,删除无用的包
3. go get
下载指定版本的依赖包,不会编译,安装(只下载代码)
go get -u(upgrade)命令会将项目中的包升级到最新版本
go get [包名]@[版本号]命令会下载对应包的指定版本或者将对应包升级到指定的版本
4. go install
会对指定的包执行下载,编译和安装,