Injecting Golang variables at build time

February 20th, 2021 on ols.wtf

Just a quick one to share something useful I learnt about injecting variable values at build time in Golang. The usecase for this was adding a Slack webhook URL to a GUI application without either shipping the webhook URL in the code, or expecting the end user to set an ENV VAR with the webhook URL in it.

Since learning this, I have decided to add /info endpoints into my applications that have the commit hash and date in them, for troubleshooting purposes.

First we need to define the variables in code

var (
        commitHash string
        commitDate string
)

Then we need to define our struct which will contain the commit data returned as JSON

type Info struct {
        CommitHash string `json:"commit"`
        CommitDate string `json:"date"`
}

We then create a function that will return this data as JSON in a HTTP response

func getInfo(w http.ResponseWriter, r *http.Request) {
        info := Info{
                CommitHash: commitHash,
                CommitDate: commitDate,
        }
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(info)
}

I added this to my main() as a new route, but you can do it however you like I suppose

func main() {
        [..]
    http.HandleFunc("/info", getInfo)
    [..]
}

If we were to build this without injecting the values, then the response would just be blank, so it’s not the end of the world if the process to inject the values doesn’t work for whatever reason (assuming you have adequate error handling of course)

curl localhost:1314/info
{"commit":"","date":""}

We then need to build the application with additional linker flags containing a reference to the variable, and the value it should have. I’ve added this to a Makefile, but you don’t have to:

go build -ldflags "-X main.commitHash=$$(git rev-parse --short HEAD) -X main.commitDate=$$(git log -1 --format=%ct)"

And now when we curl the /info endpoint, we get useful data back

curl localhost:1314/info
{"commit":"6d168d3","date":"1613819194"}

Marvellous. You can see this in action on my avatar-from-string endpoint at https://ols.wtf/avatar/info


Do you have a comment to make on this content? Start a discussion in my public inbox by emailing ~ols/public-inbox@lists.sr.ht. You can see the inbox here.