go mod作用
Go.mod是Golang1.11版本新引入的官方包管理工具用于记录依赖包具体版本的问题,方便依赖包的管理。
与传统依赖区别
传统go依赖包首先在vendor里找,如果vendor里没有依赖则从gopath/src里找,如果还没有则从goroot里找,如果还没有就报错了。传统go project建立在gopath/src下,使用go mod后则可以建立在任意目录下,依赖通过go.mod文件查找
go mod使用方法
1.首先将go的版本升级为1.11以上
2.设置GGO111MODULE=“on”
go mod命令
➜ test go help mod
Go mod provides access to operations on modules.
Note that support for modules is built into all the go commands,
not just 'go mod'. For example, day-to-day adding, removing, upgrading,
and downgrading of dependencies should be done using 'go get'.
See 'go help modules' for an overview of module functionality.
Usage:
go mod <command> [arguments]
The commands are:
download download modules to local cache
edit edit go.mod from tools or scripts
graph print module requirement graph
init initialize new module in current directory
tidy add missing and remove unused modules
vendor make vendored copy of dependencies
verify verify dependencies have expected content
why explain why packages or modules are needed
Use "go help mod <command>" for more information about a command.
使用示例
1、任意目录建立一go project,本例为/opt/test
2、示例代码
package main
import (
"fmt"
"github.com/Shopify/sarama"
)
func main() {
var ver sarama.KafkaVersion
fmt.Println("Hello, world!")
fmt.Println("kafkaversion:", ver)
}
3、 go mod init + 模块名称 初始化模块
go mod init main
运行完之后,会在当前目录下生成一个go.mod文件,这个文件为管理依赖文件
4、go run main.go
直接运行程序,不需要先下载依赖包到src下,自动会下载
Hello, world!
kafkaversion: 0.0.0.0
5、cat go.mod
module main
go 1.14
require github.com/Shopify/sarama v1.26.4
相关说明
go mod依赖下载位置
依赖的第三方包被下载到了$GOPATH/pkg/mod路径下
ls /opt/gopath/pkg/mod/github.com/ |grep "shopify"
!shopify