前言
在 Go 语言中,我们通常用借用一些工具作为可执行程序使用。但是按照官方文档安装过程中,总是会发生 go get 成功了,但是执行命令的时候总是提示命令未找到的错误,例如:Mac: bash: /Users/libin/go/bin/xxx: No such file or directory、Windows: xxx不是内部或外部命令,也不是可运行的程序或批处理文件
在常用的工具中,拿 protoc-gen-go 和 wire 来举例,需要文档的安装命令是:
go get github.com/google/wire/cmd/wire
如果你在非 go.mod 执行该程序会提示找不到 go.mod 的错误,例如:
localhost:bin libin$ go get github.com/google/wire/cmd/wire
go: go.mod file not found in current directory or any parent directory.
        'go get' is no longer supported outside a module.
        To build and install a command, 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.mod 目录执行该命令,当然可以运行成功。但是问题是,虽然成功了,但是你无法在任意目录执行该应用程序,例如:
localhost:bin libin$ wire
bash: /Users/libin/go/bin/wire: No such file or directory
解决过程
原因分析
在 Go 1.3 之前,由于采用的是 GOPATH 模式,用以上的安装方法当然没问题,因为下载的包,最后会编译为可执行程序后安装到项目的bin目录。
在 Go 1.4 之后,采用了 go mod 模式,如果使用 go get 安装,则无法安装到执行的 bin 目录,所以我们要做的是想办法让程序安装到 $GOPATH/bin 目录,这样你就可以在全局使用该执行程序了。
小贴士:
可用
go env命令查看更多 go 配置信息,包括 go 的环境变量配置。建议将$GOPATH/bin加入系统环境变量$PATH中。
解决方案
在任意目录处,使用 install 安装程序
go install github.com/google/wire/cmd/wire@latest
上面的命令会在$GOPATH/bin中生成一个可执行程序wire。这样我们就可以在任意目录使用该程序了。
localhost:~ libin$ wire help
Usage: wire <flags> <subcommand> <subcommand args>
Subcommands:
        check            print any Wire errors found
        commands         list all command names
        diff             output a diff between existing wire_gen.go files and what gen would generate
        flags            describe all known top-level flags
        gen              generate the wire_gen.go file for each package
        help             describe subcommands and their syntax
        show             describe all top-level provider sets
Use "wire flags" for a list of top-level flags
补充知识
go install 和 go get 的区别
go install命令可以接受一个版本后缀了,(例如,go install sigs.k8s.io/kind@v0.9.0),并且它是在模块感知的模式下运行,可忽略当前目录或上层目录的go.mod文件。这对于在不影响主模块依赖的情况下,安装二进制很方便go install被设计为“用于构建和安装二进制文件”,go get则被设计为 “用于编辑 go.mod 变更依赖”
go get 其他参数介绍
- -d 只下载不安装
 - -f 只有在你包含了 -u 参数的时候才有效,不让 -u 去验证 import 中的每一个都已经获取了,这对于本地 fork 的包特别有用
 - -fix 在获取源码之后先运行 fix,然后再去做其他的事情
 - -t 同时也下载需要为运行测试所需要的包
 - -u 强制使用网络去更新包和它的依赖包
 - -v 显示执行的命令
 
原文链接:https://www.yipwinghong.com/2021/12/10/Go_engineering-specification-design