mozey
mozey

Reputation: 2292

Golang compile environment variable into binary

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

Upvotes: 27

Views: 25219

Answers (3)

Ainar-G
Ainar-G

Reputation: 36249

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.

Upvotes: 38

Cody A. Ray
Cody A. Ray

Reputation: 6027

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:

  1. Declare the version as var version string
  2. Compile with -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"

Upvotes: 14

icza
icza

Reputation: 418437

There is an os.Setenv() function which you can use to set environment variables.

So you can start your application by setting the environment variable like this:

func init() {
    os.Setenv("VERSION", "0.123")
}

If you don't want to do this by "hand", you could create a tool for this which would read the current value of the VERSION environment variable and generate a .go source file in your package containing exactly like the code above (except using the current value of the VERSION environment variable). You can run such code generation by issuing the go generate command.

Read the Generating code blog post for more details about go generate.

Upvotes: 4

Related Questions