Notes & TILs
Search…
Add version info in Go projects
08 Jan, 2021 Go offers a nice way to specify version information at compile time using the -ldflags flag in go build command.

How to use it effectively ?

Just declare a -v flag in your application using the flag package
1
// yourapp.go
2
import (
3
"os"
4
"flag"
5
)
6
​
7
var AppVersion string = "dev"
8
​
9
func main() {
10
​
11
Version := flag.Bool("v", false, "Prints Current AreYouOk Version")
12
if *Version {
13
fmt.Println(AppVersion)
14
os.Exit(0)
15
}
16
}
Copied!
Now compile this & provide the value for AppVersion variable at compile time
1
go build -ldflags="-X 'main.AppVersion=v1.0.0'"
Copied!
Test if it works by running ./yourapp -v
Last modified 1mo ago