Golang compiles binary environment variable

If I compile this program

package main import ( "fmt" "os" ) var version = os.Getenv("VERSION") func main() { fmt.Println(version) } 

It prints env var when I run it

 VERSION="0.123" ./example > 0.123 

Is there a way to compile env var into a binary, for example:

 VERSION="0.123" go build example.go 

Then get the same output at startup

 ./example 
+10
go
source share
4 answers

Go 1.5 and above edit:

The syntax has changed at the moment. Use

 go build -ldflags "-X main.Version=$VERSION" 

on Linux and on Windows

 go build -ldflags "-X main.Version=%VERSION%" 

To do this, use the linker flag -X . In your case, you would do

 go build -ldflags "-X main.Version $VERSION" 

Edit: on Windows it will be

 go build -ldflags "-X main.Version %VERSION%" 

Additional information in linker documents .

+17
source share

Ainer-G's answer led me to the right place, but this was not a complete code example answering the question. A couple of changes were needed:

  1. Declare the version as var version string version var version string
  2. Compile with -X main.version=$VERSION

Here is the complete code:

 package main import ( "fmt" ) var version string func main() { fmt.Println(version) } 

Now compile with

 go build -ldflags "-X main.version=$VERSION" 
+4
source share

There is a os.Setenv() function that you can use to set environment variables.

So, you can start your application by setting the environment variable as follows:

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

If you do not want to do this with a โ€œhandโ€, you can create a tool for this that will read the current value of the VERSION environment variable and generate the source .go file in your package, containing exactly the same as the code above (except for using the current value of the variable VERSION environments). You can start this code generation by issuing the go generate command.

For more information, see Code Generation for more details on go generate .

+3
source share

The simplest solution, just a chain of commands:

Instead:

 VERSION="0.123" go build example.go 

Do:

 go build example.go && VERSION="0.123" ./example 
-one
source share

All Articles