Golang : Add build version and other information in executables
Problem:
You want to add version and other information such as compilation time into your executables(binaries) and display the information during run time. How to do that?
Solution:
Displaying version and compilation time information during run time can be useful for testing and debugging purpose. For example, you are a developer producing different versions of executable for the testing team to test and having this sort of information can assist the test team in providing accurate feedback.
Below is a simple example of how to include version and compilation time information during compilation time.
package main
import (
"fmt"
"time"
)
var (
version string
timeStamp string
)
func main() {
timeStamp := time.Now()
fmt.Println("Running version : ", version)
fmt.Println("Build time: ", timeStamp)
}
and build this file with -ldflags
flag
For example:
go build -ldflags "-X main.version=v1.1" buildinfo.go
when executing the binary, you will see this during run time:
$ ./buildinfo
Running version : v1.1
Build time: 2017-02-15 14:35:35.598182767 +0800 SGT
Hope this helps!
Happy coding!
NOTES:
If you encounter this error message during compilation time:
-X flag requires argument of the form importpath.name=value
simply change "-X main.version v0.1"
to "-X main.version=v0.1"
References:
https://www.socketloop.com/tutorials/golang-setting-variable-value-with-ldflags
See also : Golang : Setting variable value with ldflags
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.4k Javascript : How to loop over and parse JSON data?
+16.2k Golang : Clone with pointer and modify value
+6.5k Golang : Command line ticker to show work in progress
+4.8k Unix/Linux : How to open tar.gz file ?
+9.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+4.8k Fix fatal error: evacuation not done in time problem
+28k Golang : missing Git command
+8.9k Golang : Get current, epoch time and display by year, month and day
+6.4k Golang : Example of how to detect which type of script a word belongs to
+6.8k Golang : Scan files for certain pattern and rename part of the files
+15k Golang : Execute terminal command to remote machine example
+17.3k Golang : Get path name to current directory or folder