009: Set variables at build time with -LDFLAGS
I talk about how I'm using the -LDFLAGS to inject variables value at build time so it's easier to grab the exact Git commit hash that user are using when reporting issues.
Usage of -ldflags:
go build -ldflags "-X main.varName=from_build" -o mycli
Inside your code:
var varName string
func main() {
fmt.Println(varName) // prints "from_build"
}
Here's what I'm using for StaticBackend -v flag:
go build -ldflags \
"-X github.com/staticbackendhq/core/config.BuildTime=$(shell date +'%Y-%m-%d.%H:%M:%S') \
-X github.com/staticbackendhq/core/config.CommitHash=$(shell git log --pretty=format:'%h' -n 1) \
-X github.com/staticbackendhq/core/config.Version=$(shell git describe --tags)" \
-o staticbackend
Links:
go build -ldflags "-X main.varName=from_build" -o mycli
Inside your code:
var varName string
func main() {
fmt.Println(varName) // prints "from_build"
}
Here's what I'm using for StaticBackend -v flag:
go build -ldflags \
"-X github.com/staticbackendhq/core/config.BuildTime=$(shell date +'%Y-%m-%d.%H:%M:%S') \
-X github.com/staticbackendhq/core/config.CommitHash=$(shell git log --pretty=format:'%h' -n 1) \
-X github.com/staticbackendhq/core/config.Version=$(shell git describe --tags)" \
-o staticbackend
Links:
- StaticBackend website
- StaticBackend GitHub repo
- Build SaaS apps in Go (my online course and book)
Creators and Guests
![Dominic St-Pierre](https://img.transistor.fm/HCtTIm4fjr-PPNKVTdewmxYFfFJgSQJkWYmXjb1QLug/rs:fill:400:400:1/q:60/aHR0cHM6Ly9pbWct/dXBsb2FkLXByb2R1/Y3Rpb24udHJhbnNp/c3Rvci5mbS9wZXJz/b24vZjIxMjQyNjAt/NDMwMy00ZWYzLWIz/MDQtMGU0ZTMxNjZl/ZGQ5LzE3MDcxNDYy/MzYtaW1hZ2UuanBn.webp)
Host
Dominic St-Pierre
Go system builder - entrepreneur. I've been writing software systems since 2001. I love SaaS, building since 2008.
![009: Set variables at build time with -LDFLAGS](https://img.transistor.fm/bF6iLV4xtxdYH5mX8t_vf_A5r7knvK8pvJT3yTiumtQ/rs:fill:800:800:1/q:60/aHR0cHM6Ly9pbWct/dXBsb2FkLXByb2R1/Y3Rpb24udHJhbnNp/c3Rvci5mbS9zaG93/LzI3MjkyLzE2NDE1/NjU2MDgtYXJ0d29y/ay5qcGc.webp)