Skip to content

Instantly share code, notes, and snippets.

@piotrpersona
Last active May 10, 2024 01:42
Show Gist options
  • Save piotrpersona/ef4c5faaef07987d176d513e23cd9d0f to your computer and use it in GitHub Desktop.
Save piotrpersona/ef4c5faaef07987d176d513e23cd9d0f to your computer and use it in GitHub Desktop.
Golang build ldflags
GIT_TAG="$( git describe --abbrev=0 )"
GIT_HASH="$( git rev-parse HEAD )"
BUILD_DATE="$( date +%F )" # Note: An ldflag cannot contain whitespace
REPO="github.com/user/repo"
OUTPUT_NAME="build-artifact"
PACKAGE="main.go"
read -r -d '' LDFLAGS << EOM
-X ${REPO}/cmd.gitVersionTag=${GIT_TAG}
-X ${REPO}/cmd.gitHash=${GIT_HASH}
-X ${REPO}/cmd.buildDate=${BUILD_DATE}
EOM
go build -ldflags "${LDFLAGS}" \
-o "${GOPATH}/bin/${OUTPUT_NAME}" "${PACKAGE}"
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var gitHash, gitVersionTag, buildDate string
// versionCmd represents the version command
var versionCmd = &cobra.Command{
Use: "version",
Short: "Display version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("version: %s\n", gitVersionTag)
fmt.Printf("hash: %s\n", gitHash)
fmt.Printf("build date: %s\n", buildDate)
},
}
func init() {
rootCmd.AddCommand(versionCmd)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment