https://talks.godoc.org/github.com/myitcv/talks/2018-08-15-glug-modules/main.slide#1git
Modules是Go 1.11中新增的實驗性功能,基於vgo演變而來,是一個新型的包管理工具。github
這些包管理工具都是基於GOPATH
或者vendor
目錄,並不能很好的解決不一樣版本依賴問題。Modules是在GOPATH
以外一套新的包管理方式。golang
首先要把go升級到1.11。json
升級後,能夠設置經過一個環境變量GO111MODULE
來激活modules:windows
當module功能啓用時,GOPATH
在項目構建過程當中再也不擔當import的角色,但它仍然存儲下載的依賴包,具體位置在$GOPATH/pkg/mod
。緩存
Go1.11新增了命令go mod
來支持Modules的使用。app
> 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.
首先建立一個項目helloworld:ide
cd && mkdir helloworld && cd helloworld
而後建立文件main.go
並寫入:工具
package main import ( log "github.com/sirupsen/logrus" ) func main() { log.WithFields(log.Fields{ "animal": "walrus", }).Info("A walrus appears") }
初始化mod:ui
go mod init helloworld
系統生成了一個go.mod
的文件:
module helloworld
而後執行go build,再次查看go.mod文件發現多了一些內容:
module helloworld require github.com/sirupsen/logrus v1.1.1
同時多了一個go.sum
的文件:
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.1.1 h1:VzGj7lhU7KEB9e9gMpAV/v5XT2NVSvLJhJLCWbnkgXg= github.com/sirupsen/logrus v1.1.1/go.mod h1:zrgwTnHtNr00buQ1vSptGe8m1f/BbgsPukg8qsT7A+A= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793 h1:u+LnwYTOOW7Ukr/fppxEb1Nwz0AtPflrblfvUudpo+I= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33 h1:I6FyU15t786LL7oL/hn43zqTuEGr4PN7F4XJ1p4E3Y8= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
go.sum不是一個鎖文件,是一個模塊版本內容的校驗值,用來驗證當前緩存的模塊。go.sum包含了直接依賴和間接依賴的包的信息,比go.mod要多一些。
有四種指令:module,require,exclude,replace。
go mod tidy //拉取缺乏的模塊,移除不用的模塊。
go mod download //下載依賴包
go mod graph //打印模塊依賴圖
go mod vendor //將依賴複製到vendor下
go mod verify //校驗依賴
go mod why //解釋爲何須要依賴
go list -m -json all //依賴詳情