如题,这是我常在在项目中使用到的Makefile和main.go文件,在程序执行的时候就可以知道git commit
、version
和built time
,方便版本管理和更新迭代,以及问题排查。
Makefile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
NAME := gw
VERSION ?= 0.0.1
COMMIT := $(shell git log -n 1 --pretty=format:"%h")
BRANCH := $(shell git name-rev --name-only HEAD)
NOW := $(shell date +%F_%T)
VARS := -X main.GitCommit=$(COMMIT) -X main.Version=$(VERSION) -X main.BuiltTime=$(NOW) -X main.GitBranch=$(BRANCH)
ifeq ($(strip $(DEBUG)), true)
BUILD_ARGS = -v -gcflags="all=-N -l"
else
BUILD_ARGS = -v -trimpath \
-gcflags="all=-trimpath=$(PWD)" \
-asmflags="all=-trimpath=$(PWD)" \
-ldflags '-extldflags "-static"'
endif
GOBUILD=go build $(BUILD_ARGS)
export GO111MODULE=on
build:
GOOS=linux GOARCH=amd64 $(GOBUILD) -o bin/$(NAME) .
deps:
go mod tidy -v
.PHONY:build
|
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
var (
help bool
conf string
Version string
BuiltTime string
GitCommit string
GitBranch string
)
func init() {
flag.BoolVar(&help, "h", false, "帮助信息")
flag.StringVar(&conf, "c", "", "配置文件")
}
func main() {
flag.Parse()
if help {
flag.Usage()
fmt.Printf("\nversion: %s, commit: %s, branch: %s, built at: %s.\n",
Version, GitCommit, GitBranch, BuiltTime)
os.Exit(0)
}
// your code here ...
}
|