在 Go 1.11 中 ,官方加入package management tool,稱爲Go Modules。Go mod 沒有出現以前,用的最多的包管理器就是 govendor、glide等,這些工具都未達到Go對包管理的預期,好比每次下載,好比牆外下載,好比對GOPATH的依賴,好比多版本的控制等等。而後Go Modules就出現了,它不依賴於GOPATH,只跟項目有關,能夠指定代理,能夠很容易的經過版本進行控制,擺脫GOPATH的依賴,也爲Go之後的自由發展奠基了基礎。git
命令 | 描述 |
---|---|
go init | 在當前目錄項目下初始化mod |
go tidy | 拉取依賴的模塊,移除不用的模塊 |
go vendor | 將依賴複製到vendor下 |
go edit | 編輯go.mod |
go verify | 驗證依賴是否正確 |
其實工做基本上都使用init和tidy就夠了。github
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.iogolang
source ~/.bash_profilevim
建立項目 myproject
main.gobash
package main import ( "github.com/satori/go.uuid" "fmt" ) func main() { uid := uuid.NewV4() fmt.Println(uid) }
執行Go mod命令, init 和 tidy服務器
go mod init go: creating new go.mod: module myproject go mod tidy go: finding golang.org/x/tools latest go: downloading golang.org/x/tools v0.0.0-20200415034506-5d8e1897c761 go: extracting golang.org/x/tools v0.0.0-20200415034506-5d8e1897c761 go: finding gopkg.in/check.v1 latest go: downloading gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f go: extracting gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f go: finding github.com/niemeyer/pretty latest go: downloading github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e go: extracting github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e go: downloading github.com/kr/text v0.1.0 go: extracting github.com/kr/text v0.1.0
編譯執行結果ide
go build main.go ./main 6723138d-ab2c-4de6-b996-732362985548
能夠看下Go mod生成的最主要的文件 go.mod工具
cat go.mod module myproject go 1.13 require ( github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect github.com/satori/go.uuid v1.2.0 gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect )
每一個包後面都跟了一個版本。若是想切換分支的話,後面的版本能夠任意切換到須要的分支上,好比ui
require ( github.com/niemeyer/pretty master github.com/satori/go.uuid v1.2.0 gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect )
也可使用本地代碼替換遠程代碼分支。就可使用下面的
/data/www/go/src/go.uuid 代替遠程分支 github.com/satori/go.uuid。
在go.mod最後一行加上下面的代碼代理
replace github.com/satori/go.uuid => /data/www/go/src/go.uuid
Go mod的使用是否是特別簡單。