I am creating an app using Go 1.9.2 and I am trying to add a version string variable to it using the ldflags -X
options during the build.
I\'ve managed to s
Here's a simple example, hopefully it would clarify and help how to do it easily:
Create a directory for your application:
$ mkdir app && cd app
Create a sub directory config
:
$ mkdir config
Add the following file. it should be under app/config/vars.go
:
package config
var Version string
var BuildTime string
//todo: can add as many as build vars
In the root app/
, add main package main.go
:
package main
import (
"fmt"
"app/config"
)
func main() {
fmt.Println("build.Version:\t", Version)
fmt.Println("build.Time:\t", build.BuildTime)
}
Now it is time to build:
go build -ldflags "-X 'app/config.Version=0.0.1' -X 'app/config.BuildTime=$(date)'"
Once it's built, you can run now the app:
$ ./app
Version: 0.0.1
build.Time: Sat Jul 4 19:49:19 UTC 2020
Finally, you may need sometimes to explore what does specific app you didn't code yourself provide in ldflags
, you can do this by using nm
that comes with go tool
to list all ldflags
.
Just build the app then use go tool nm
to list all linker flags.
$ go build -o app
$ go tool nm ./app
Still have any questions or anything to be more clarified? please feel free to leave a comment below and I will get back to you as soon as I can.