Go1-17 新特性:go get 變了

大家好,我是 polarisxu。

爲什麼把 Go 的一些小變化單獨寫文章,而不是一篇文章介紹所有的變化?主要是想讓大家對某一個特性有更深的記憶。全部列出,很容易一眼而過,過段時間就忘記了。但一個變化,專門一篇文章介紹,更容易記住。

01 安裝命令會警告

一直以來,go get 用於下載並安裝 Go 包、命令等,而 go install 在 module 時代幾乎很少使用,在 GOPATH 年代,go install 用來編譯安裝本地項目。

自 1.16 起,官方說,不應該 go get 下載安裝命令(即可執行程序),不過只是這麼說,卻依然可以使用。

但 Go1.17 開始,如果使用 go get 安裝命令,會警告:

$ go get github.com/github/hub
go get: installing executables with 'go get' in module mode is deprecated.
 To adjust and download dependencies of the current module, use 'go get -d'.
 To install using requirements of the current module, use 'go install'.
 To install ignoring the current module, use 'go install' with a version,
 like 'go install example.com/cmd@latest'.
 For more information, see https://golang.org/doc/go-get-install-deprecation
 or run 'go help get' or 'go help install'.

也就是說,go get 只用來下載普通的包,安裝可執行程序,應該使用 go install。

$ go install github.com/github/hub

這會將 hub 命令安裝到 $GOBIN 下。

此外,go get 有一個 flag -d,指示 go get 下載對應的包,但不做編譯和安裝。將來的版本,-d 會成爲默認行爲,這樣會更快。此外,因爲不編譯,即使目標依賴在特定平臺編譯報錯,go get 也能正常執行完。

至於爲什麼用 go install 代替 go get 執行命令安裝,這裏有詳細的說明:https://docs.studygolang.com/doc/go-get-install-deprecation,簡單說就是和命令的語義更符合。

告訴大家一個參與開源項目的機會:

如果某個項目提供了怎麼安裝可執行文件的方法,大概率使用的是 go get,你可以提交一個 PR,將其改爲 go install,哈哈哈~

02 廢棄 -insecure

go get 的這個 flag 使用的人可能不多。什麼時候會用到呢?Go1.16 版本關於這個 flag 的說明:

The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP, and also bypassess module sum validation using the checksum database. Use with caution. This flag is deprecated and will be removed in a future version of go. To permit the use of insecure schemes, use the GOINSECURE environment variable instead. To bypass module sum validation, use GOPRIVATE or GONOSUMDB. See 'go help environment' for details.

這主要用來處理私有倉庫沒有提供 HTTPS 的情況,同時避免進行數據庫校驗和檢查。不過更建議使用 GOINSECURE 環境變量。看看這個環境變量的說明:

GOINSECURE Comma-separated list of glob patterns (in the syntax of Go's path.Match) of module path prefixes that should always be fetched in an insecure manner. Only applies to dependencies that are being fetched directly. Unlike the -insecure flag on 'go get', GOINSECURE does not disable checksum database validation. GOPRIVATE or GONOSUMDB may be used to achieve that.

Go1.17 直接廢棄了 -insecure 這個 flag,必須使用 GOINSECURE 環境變量。但這個環境變量不會禁用數據庫校驗和檢查。

因此,對於私有倉庫,如果沒有提供 HTTPS,應該配置 GOINSECURE,指明哪些地址啓用 INSECURE 模式,同時配置 GOPRIVATE 環境變量,避免數據庫校驗和檢查。

$ go get -insecure github.com/labstack/echo/v4
go get: -insecure flag is no longer supported; use GOINSECURE instead

03 總結

建議你實際動手試試 go get 命令,同時切換不同的 Go 版本,看看效果,以加深印象。對其中有任何疑問,都可以通過 go 命令的相關幫助找到。比如查看具體環境變量的意思,可以 go help environment 查看 Go 提供的所有環境變量。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/jyr2mdq7hAOy7wKpBJHMgQ