七叶笔记 » golang编程 » Go1.17 新特性:go get 变了

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 
 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 执行命令安装,这里有详细的说明:,简单说就是和命令的语义更符合。

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 提供的所有环境变量。

相关文章