If I compile this program
package main
import (
"fmt"
"os"
)
var version = os.Getenv("VERSION")
func main() {
fmt.Println(version)
}
It prints the env var when I run it
VERSION="0.123" ./example
> 0.123
Is there a way to compile the env var into the binary, for example:
VERSION="0.123" go build example.go
Then get the same output when I run
./example
Go is a compiled language. Source code belonging to a Go project must be run through a compiler. The compiler generates a binary which can then be used to run the program on a target OS.
Linker & LdflagsThe go build tool allows us to pass options to the Linker, which is the component responsible for assembling the binary. We can pass options to the Linker by using the --ldflags flag to the build tool. There are very many options you can pass, but in this article, we will focus on only one of them.
Go 1.5 and above edit:
As of now, the syntax has changed.
On Unix use:
go build -ldflags "-X main.Version=$VERSION"
On Windows use:
go build -ldflags "-X main.Version=%VERSION%"
This is what -X
linker flag is for. In your case, you would do
go build -ldflags "-X main.Version $VERSION"
Edit: on Windows this would be
go build -ldflags "-X main.Version %VERSION%"
More info in the linker docs.
Ainer-G's answer led me to the right place, but it wasn't a full code sample answering the question. A couple of changes were required:
var version string
-X main.version=$VERSION
Here's the full code:
package main
import (
"fmt"
)
var version string
func main() {
fmt.Println(version)
}
Now compile with
go build -ldflags "-X main.version=$VERSION"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With