告別GOPATH,如何使用go mod管理包


我們都知道在使用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.

如果在項目中使用

  1. 版本:首先將你的Go版本更新到(>=1.11),這里將不介紹怎么更新
  2. 設置環境變量(1.12默認):在你的項目目錄下使用set GO111MODULE=ON
  3. 執行go mod init在當前目錄下生成一個go.mod文件,如果之前有生成過需要刪除再初始化

執行完上面步驟基本就完成了,運行下程序你會發現目錄下多了一個go.sum文件,是用來記錄所依賴的版本的鎖定

執行命令go mod verify命令來檢查當前模塊的依賴是否全部下載下來,是否下載下來被修改過。如果所有的模塊都沒有被修改過,那么執行這條命令之后,會打印all modules verified

總結

使用go mod后你會發現在GOPATH下面的pkg目錄會有一個mod目錄,里面包含了項目需要的依賴包,這也是為什么不需要再GOPATH中開發程序也能使用的原因


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM