《Go 环境变量与工作目录》
在 Go 1.11 之前,GOPATH 是唯一的工程组织方式;使用 go mod 后不再是强制约定,但理解它仍有帮助。
1. GOPATH 的三级目录
$GOPATH/src— 存放源代码(main包所在目录)。$GOPATH/pkg— 存放编译打包后的包对象。$GOPATH/bin— 存放编译得到的可执行文件。
2. 编译时注入版本信息(-ldflags)
在 Go 编译时通过 -ldflags 注入版本号、git 提交哈希与构建时间:
// version.go
package main
import (
"fmt"
"os"
)
var (
gitHash string
buildTime string
goVersion string
)
func main() {
args := os.Args
if len(args) == 2 && (args[1] == "--version" || args[1] == "-v") {
fmt.Printf("Git Commit Hash: %s \n", gitHash)
fmt.Printf("Build TimeStamp: %s \n", buildTime)
fmt.Printf("GoLang Version: %s \n", goVersion)
return
}
}
构建脚本 build.sh:
go build -ldflags \
"-X 'main.goVersion=$(go version)'
-X 'main.gitHash=$(git show -s --format=%H)'
-X 'main.buildTime=$(git show -s --format=%cd)'" \
-o main
3. 常用工具链
- 单元测试:
go test - 性能分析 pprof:
go tool pprof
资源
- 单元测试参考:https://www.flysnow.org/2017/05/16/go-in-action-go-unit-test.html
- pprof 性能分析:https://colobu.com/2017/03/02/a-short-survey-of-golang-pprof/
阅读 —
·
全站 —