runsisi's

technical notes

go 工具使用 tips

2019-04-03 runsisi#golang

go build -x

列出 go build 过程中的所有命令执行过程,类似于 bash 的 -x 选项:

~$ go build -x
WORK=/tmp/go-build044494183
mkdir -p $WORK/b001/
cat >$WORK/b001/importcfg.link << 'EOF' # internal
packagefile github.com/runsisi/zstor-ctl=/home/runsisi/.cache/go-build/3e/3ee7302e3f925630f468ed6c8f38c1e690e11f0c35b1c1a1075859f9c4511cd2-d
packagefile github.com/runsisi/zstor-ctl/cmd=/home/runsisi/.cache/go-build/7d/7d16050f610d368f82c74e767e92782e2a77e485c0252716d6d7212508c60b3e-d
packagefile runtime=/usr/lib/go-1.12/pkg/linux_amd64/runtime.a
packagefile fmt=/usr/lib/go-1.12/pkg/linux_amd64/fmt.a
...

go tool

列出所有的 go tool 子命令:

~$ go tool
addr2line
api
asm
buildid
cgo
compile
cover
dist
doc
fix
link
nm
objdump
pack
pprof
test2json
trace
vet

查看 go tool 子命令帮助文档:

~$ go doc cmd/compile
Compile, typically invoked as “go tool compile,” compiles a single Go
package comprising the files named on the command line. It then writes a
single object file named for the basename of the first source file with a .o
suffix. The object file can then be combined with other objects into a
package archive or passed directly to the linker (“go tool link”). If
invoked with -pack, the compiler writes an archive directly, bypassing the
intermediate object file.
...
~$ go doc cmd/link
Link, typically invoked as “go tool link,” reads the Go archive or object
for a package main, along with its dependencies, and combines them into an
executable binary.
...

go build -gcflags

提供编译选项,如禁用编译器优化和内联(go1.10 之前的版本):

~$ go build -gcflags="-N -l"

go1.10+ 版本:

~$ go build -gcflags="all=-N -l"

具体支持的编译选项可以参考 go doc cmd/compile 帮助文档中 Flags 一节。

go build -ldflags

提供链接选项,如为包中的变量赋值:

~$ go build -ldflags "-X github.com/runsisi/zstor-ctl/cmd.Version=$(git describe)"

如果要传递的字符串可能存在空白字符,则需要用引号括起来:

~$ go run -ldflags "-X '${GIT_IMPORT}.Version=${GIT_DESCRIBE}${GIT_DIRTY}' ${LD_FLAGS}"

注意其中的单引号是在双引号内部,所以里面的 shell 变量会展开。

具体支持的编译选项可以参考 go doc cmd/link 帮助文档中 Flags 一节。

go list -m

列出项目当前所有的依赖模块:

$ go list -m all
github.com/spf13/cobra
github.com/BurntSushi/toml v0.3.1
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6
github.com/coreos/etcd v3.3.10+incompatible
...

列出匹配规则指定的依赖模块:

~$ go list -m github.com/spf...
github.com/spf13/cobra
github.com/spf13/afero v1.1.2
github.com/spf13/cast v1.3.0
github.com/spf13/jwalterweatherman v1.0.0
github.com/spf13/pflag v1.0.3
github.com/spf13/viper v1.3.2
~$ go list -m ...mitche...
github.com/mitchellh/go-homedir v1.1.0
github.com/mitchellh/mapstructure v1.1.2

-m 选项要求 Go1.11+ 版本,且需要启用 module 特性,对于 Go1.11 或 Go1.12 要么设置环境变量 GO111MODULE=on,要么设置环境变量 GO111MODULE=auto 且项目代码在 $GOPATH/src 之外,Go1.13+ 版本将默认启用 module 特性(类似于 GO111MODULE=on)。

参考资料

Go tooling essentials

https://rakyll.org/go-tool-flags/

go list, your Swiss army knife

https://dave.cheney.net/2014/09/14/go-list-your-swiss-army-knife