我們都知道在使用Golang時開發程序時都需要在 GOPATH
下面,這就非常不方便。如果你想放在磁盤上的其他地方,那么go mod將是你的“好伙伴”。
關於 go mod 的說明,可以參考:
命令行說明
➜ ~ go 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 下載依賴的 module 到本地 cache edit edit go.mod from tools or scripts 編輯 go.mod graph print module requirement graph 打印模塊依賴圖 init initialize new module in current directory 在當前目錄下初始化 go.mod(就是會新建一個 go.mod 文件) tidy add missing and remove unused modules 整理依賴關系,會添加丟失的 module,刪除不需要的 module vendor make vendored copy of dependencies 將依賴復制到 vendor 下 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.
如果在項目中使用
- 版本:首先將你的Go版本更新到(>=1.11),這里將不介紹怎么更新
- 設置環境變量(1.12默認):在你的項目目錄下使用
set GO111MODULE=ON
- 執行
go mod init
在當前目錄下生成一個go.mod
文件,如果之前有生成過需要刪除再初始化
執行完上面步驟基本就完成了,運行下程序你會發現目錄下多了一個go.sum
文件,是用來記錄所依賴的版本的鎖定
執行命令go mod verify
命令來檢查當前模塊的依賴是否全部下載下來,是否下載下來被修改過。如果所有的模塊都沒有被修改過,那么執行這條命令之后,會打印all modules verified
。
總結
使用go mod
后你會發現在GOPATH
下面的pkg
目錄會有一個mod
目錄,里面包含了項目需要的依賴包,這也是為什么不需要再GOPATH
中開發程序也能使用的原因