-1

I would like to embed in the compiled binary information passed to the build process, at build time (typically a string, specifically the commit hash during my CI/CD execution).

I then would like to simply display it with fmt.Sprintf("%v", thisEmbeddedString).

I was hoping for the embed package to be a solution, but it seems to be only for files.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
WoJ
  • 27,165
  • 48
  • 180
  • 345
  • Also see [Golang - How to display modules version from inside of code](https://stackoverflow.com/questions/62009264/golang-how-to-display-modules-version-from-inside-of-code/62009359#62009359). – icza Jan 05 '22 at 10:19
  • 2
    With Go 1.18, you can get the VCS version directly from your binary with: `go version -m file `. You need to build the binary with the full main package path, not by building individual files on the command line. (`go build .` instead of `go build main.go`) Or from your code with `info, _ := debug.ReadBuildInfo(); fmt.Println(info.Settings) ` The git commit will be under the `Key` `vcs.revision`. – Dolanor Feb 15 '22 at 11:46

1 Answers1

3

Declare a variable in your code (in the example below, in main, it will be set in the next step)

var commit string

Add a flag to the build

go build -ldflags "-X main.commit=$GIT_COMMIT"

You can then access the variable as usual

log.Info().Msgf("commit → %v", commit)
WoJ
  • 27,165
  • 48
  • 180
  • 345