一、使用手冊
1. 使用方法:
go mod <command> [arguments]
2. 具體命令
download: download modules to local cache(下載依賴包)edit: edit go.mod from tools or scripts(編輯 go.mod)graph: print module requirement graph(打印模塊依賴圖)init: initialize new module in current directory(在當前目錄初始化 mod)tidy: add missing and remove unused modules(拉取缺少的模塊,移除不用的模塊)vendor: make vendored copy of dependencies(將依賴複製到vendor下)verify: verify dependencies have expected content(驗證依賴是否正確)why: explain why packages or modules are needed(解釋爲什麼需要依賴)
二、使用前準備
1. 終端輸入
export GO111MODULE=on
2. GO111MODULE 說明
GO111MODULE
有三個值:off
, on
和auto(默認值)
(1)off
,go命令行將不會支持module功能,尋找依賴包的方式將會沿用舊版本那種通過vendor目錄或者GOPATH模式來查找
(2)on
,go命令行會使用modules,而一點也不會去GOPATH目錄下查找
(3)auto
,默認值,go命令行將會根據當前目錄來決定是否啓用module功能;這種情況下可以分爲兩種情形:
當前目錄在GOPATH/src之外且該目錄包含go.mod文件
當前文件在包含go.mod文件的目錄下面
三、具體示例
1. 創建一個新項目
(1)在 GOPATH 目錄之外新建一個目錄,並使用 go mod init 初始化生成 go.mod 文件
$ go mod init test
go: creating new go.mod: module test
$ cat go.mod
module test
go 1.13
(2)go.mod 提供了module, require、replace和exclude 四個命令
module 語句指定包的名字(路徑)
require 語句指定的依賴項模塊
replace 語句可以替換依賴項模塊
exclude 語句可以忽略依賴項模塊
2. 添加依賴
# test.go
package main
import (
"net/http"
"github.com/labstack/echo"
)
func main() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.Logger.Fatal(e.Start(":1323"))
}
執行 go run test.go
運行代碼會發現 go mod 會自動查找依賴自動下載
$ cat go.mod
module test
go 1.13
require (
github.com/labstack/echo v3.3.10+incompatible
github.com/labstack/gommon v0.3.0 // indirect
golang.org/x/crypto v0.0.0-20191219195013-becbf705a915 // indirect
)