Search code examples
gobuildembed

How to embed a string in the compiled binary at build time?


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.


Solution

  • 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)