编译命令示例:
date
GOOS=linux GOARCH=amd64 go env GOOS GOARCH GOPROXY
GOOS=linux GOARCH=amd64 go mod vendor
time GOOS=linux GOARCH=amd64 go build -mod=vendor -ldflags="-X 'main.buildDate=`TZ='Asia/Shanghai' date +"%FT%T,%A"`' -X main.gitBranch=`git rev-parse --abbrev-ref HEAD` -X main.gitCommitID=`git rev-parse HEAD` -X 'main.gitCommitDate=`git log --pretty='%cI' -n 1`' -X 'main.gitCommitSubject=`git log --pretty='%s' -n 1 | tr -d \'`'" -o bin/main main.go
代码中需接收变量值:
package main
var (
buildDate = "date" // -X 'main.buildDate=`TZ='Asia/Shanghai' date +"%FT%T,%A"`'
gitBranch = "branch" // -X main.gitBranch=`git rev-parse --abbrev-ref HEAD`
gitCommitID = "dev" // -X main.gitCommitID=`git rev-parse HEAD`
gitCommitDate = "commit_date" // -X 'main.gitCommitDate=`git log --pretty='%cI' -n 1`'
gitCommitSubject = "subject" // -X 'main.gitCommitSubject=`git log --pretty='%s' -n 1`'
)
func main() {
printWelcome()
}
func printWelcome() {
if gitCommitID == "" {
gitCommitID = "dev"
}
log.Info("-------- Welcome to use xxx Server --------")
log.Infof("Build Date : %s", buildDate)
log.Infof("Git Branch : %s", gitBranch)
log.Infof("Git Commit ID : %s", gitCommitID)
log.Infof("Git Commit Date : %s", gitCommitDate)
log.Infof("Git Commit Subject : %s", gitCommitSubject)
log.Infof("node name : %s", os.Getenv("NODE_ID"))
log.Info("------------------------------------")
}
docker Makefile示例(假如git tag了最新的commit,则push):
.PHONY: docker-build
docker-build: build ## Build docker image with the manager.
cp bin/controller .
$(CONTAINER_TOOL) build --push --platform linux/amd64 -t ${IMG} -f Dockerfile.local .
rm controller
.PHONY: push-release
push-release:
docker tag $(IMG) $(IMG_RELEASE):latest
docker push $(IMG_RELEASE):latest
@\
TAG=$(shell tagged="$$(git describe --tags --match='v*' --abbrev=0)"; if [ "$$tagged" ] && [ "$$(git rev-list -n1 HEAD)" = "$$(git rev-list -n1 $$tagged)" ]; then echo $$tagged; fi); \
if [ -n "$$TAG" ]; then \
echo ""; \
echo "latest branch tag with $$TAG, push it"; \
echo "docker tag $(IMG) $(IMG_RELEASE):$$TAG"; \
docker tag $(IMG) $(IMG_RELEASE):$$TAG; \
echo "docker push $(IMG_RELEASE):$$TAG"; \
docker push $(IMG_RELEASE):$$TAG; \
fi