使用Go mod 命令管理包

命令 描述
go mod init 在当前目录项目下初始化mod
go mod tidy 拉取依赖的模块,移除不用的模块
go mod vendor 将依赖复制到vendor下
go mod edit 编辑go.mod
go mod verify 验证依赖是否正确

其实工作基本上都使用init和tidy就够了。

设置环境变量

GO111MODULE
有三个值,off、on、auto,off 和 on 即关闭和开启,auto 则会根据当前目录下是否有 go.mod 文件来判断是否使用 modules 功能。无论使用哪种模式,module 功能默认不在 GOPATH 目录下查找依赖文件。
GOPROXY
设置代理服务,https://goproxy.io。也可以自己搭代理服务,然后把 GOPROXY 设置为代理服务器的地址。
vim ~/.bash_profile
加入配置的两行
export GO111MODULE=on
export GOPROXY=https://goproxy.io
source ~/.bash_profile

举个栗子

创建项目 myproject
main.go

  1. package main
  2. import (
  3. "github.com/satori/go.uuid"
  4. "fmt"
  5. )
  6. func main() {
  7. uid := uuid.NewV4()
  8. fmt.Println(uid)
  9. }

执行Go mod命令, init 和 tidy

  1. go mod init
  2. go: creating new go.mod: module myproject
  3. go mod tidy
  4. go: finding golang.org/x/tools latest
  5. go: downloading golang.org/x/tools v0.0.0-20200415034506-5d8e1897c761
  6. go: extracting golang.org/x/tools v0.0.0-20200415034506-5d8e1897c761
  7. go: finding gopkg.in/check.v1 latest
  8. go: downloading gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f
  9. go: extracting gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f
  10. go: finding github.com/niemeyer/pretty latest
  11. go: downloading github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e
  12. go: extracting github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e
  13. go: downloading github.com/kr/text v0.1.0
  14. go: extracting github.com/kr/text v0.1.0

编译执行结果

  1. go build main.go
  2. ./main
  3. 6723138d-ab2c-4de6-b996-732362985548

可以看下Go mod生成的最主要的文件 go.mod

  1. cat go.mod
  2. module myproject
  3. go 1.13
  4. require (
  5. github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
  6. github.com/satori/go.uuid v1.2.0
  7. gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
  8. )

每个包后面都跟了一个版本。如果想切换分支的话,后面的版本可以任意切换到需要的分支上,比如

  1. require (
  2. github.com/niemeyer/pretty master
  3. github.com/satori/go.uuid v1.2.0
  4. gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
  5. )

也可以使用本地代码替换远程代码分支。就可以使用下面的
/data/www/go/src/go.uuid 代替远程分支 github.com/satori/go.uuid。
在go.mod最后一行加上下面的代码

  1. replace github.com/satori/go.uuid => /data/www/go/src/go.uuid

Go mod的使用是不是特别简单。