Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang compile environment variable into binary

Tags:

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
like image 608
mozey Avatar asked Feb 11 '15 16:02

mozey


People also ask

Does Go compile to binary?

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.

What is Ldflags in go build?

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.


2 Answers

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.

like image 110
Ainar-G Avatar answered Sep 24 '22 18:09

Ainar-G


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"
like image 43
Cody A. Ray Avatar answered Sep 24 '22 18:09

Cody A. Ray