天天看点

将版本信息写入Go编译的二进制文件将版本信息写入Go编译的二进制文件

将版本信息写入Go编译的二进制文件

Makefile

SHELL := /bin/bash
BASEDIR = $(shell pwd)
DOCKER_TARGET=hub.docker.com/lee/hello

# build with version infos
versionDir = "main"
gitTag = $(shell if [ "`git describe --tags --abbrev=0 2>/dev/null`" != "" ];then git describe --tags --abbrev=0; else git log --pretty=format:'%h' -n 1; fi)
buildDate = $(shell TZ=UTC date +%FT%T%z)
gitCommit = $(shell git log --pretty=format:'%H' -n 1)

ldflags="-w -X ${versionDir}.gitTag=${gitTag} -X ${versionDir}.buildDate=${buildDate} -X ${versionDir}.gitCommit=${gitCommit}"

build:
	go build -ldflags ${ldflags} -o main ./

docker-build:
	docker build . -t ${DOCKER_TARGET}:$(gitTag)

docker-release:
	docker push ${DOCKER_TARGET}:$(gitTag)

           

Dockerfile

# build stage
FROM golang:1.14 as build
ENV GOPROXY="https://goproxy.io"
ENV CGO_ENABLED=0
WORKDIR /app
COPY . /app
RUN make build


# production stage
FROM alpine as production

WORKDIR /app
#COPY ./conf/ /app/conf
COPY --from=build /app/main /app
EXPOSE 8081
ENTRYPOINT ["/app/main"]


           

读取版本信息

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
)

var (
	gitTag    string
	buildDate string
	gitCommit string
)

func main() {
	args := os.Args
	if len(args) == 2 && (args[1] == "--version" || args[1] == "-v") {
        // 打印版本信息
		fmt.Printf("Git Tag: %s\n", gitTag)
		fmt.Printf("Git Commit Hash: %s\n", gitCommit)
		fmt.Printf("UTC Build Time : %s\n", buildDate)
		return
	}
	Handler := func(w http.ResponseWriter, r *http.Request) {
		hostName, err := os.Hostname()
		if err != nil {
			hostName = "unknown host"
		}
		w.Write([]byte("You've hint " + hostName + "\n"))
	}

	http.HandleFunc("/", Handler)

	log.Fatal(http.ListenAndServe(":8081", nil))
}

           

效果演示

[email protected]:~/Desktop/hello$ ./main -v
Git Tag: v1.1.0-alpha
Git Commit Hash: 34d1a1890073f581c3c8076131d184ab10270795
UTC Build Time : 2020-06-18T01:13:42+0000
           
go