概述
将版本信息写入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: %sn", gitTag)
fmt.Printf("Git Commit Hash: %sn", gitCommit)
fmt.Printf("UTC Build Time : %sn", 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))
}
效果演示
pwli@pwli-PC:~/Desktop/hello$ ./main -v
Git Tag: v1.1.0-alpha
Git Commit Hash: 34d1a1890073f581c3c8076131d184ab10270795
UTC Build Time : 2020-06-18T01:13:42+0000
最后
以上就是稳重小懒猪为你收集整理的将版本信息写入Go编译的二进制文件将版本信息写入Go编译的二进制文件的全部内容,希望文章能够帮你解决将版本信息写入Go编译的二进制文件将版本信息写入Go编译的二进制文件所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复