Go Tidbit: Setting Variables in Go During Build
Last week I was working on a Go program. I wanted it to print the closest Git tag and build time to logs at startup.
I could write a small script that generates a Go file with these two variables set right before building the Go program.
But, Go makes it easier.
Say you have the following Go code:
You can build it like so:
go build -ldflags "-X main.hello=HelloGo" -o a.out .
And run it:
The program will print
You can set any string variable with
ldflags. Just make sure to prefix the variable name with the complete package path.
For example, if your package path is
github.com/FurqanSoftware/example/cfg and the variable name is
BuildTag, then your
ldflags should look like this:
In the Go program that I was working on, I added a small
Now, if I run
make printd, the resulting binary will have the two variables
buildTime set to the closest Git tag and the time when the binary was built.
Here’s what the Go program now prints to the log at startup:
(The line “Release” has the build tag and time.)
This post is 16th of my #100DaysToOffload challenge. Want to get involved? Find out more at 100daystooffload.com.
comments powered by Disqus