简体   繁体   English

Golang 将环境变量编译成二进制

[英]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当我运行它时它会打印 env var

VERSION="0.123" ./example
> 0.123

Is there a way to compile the env var into the binary, for example:有没有办法将 env var 编译成二进制文件,例如:

VERSION="0.123" go build example.go

Then get the same output when I run然后在我运行时得到相同的输出

./example

Go 1.5 and above edit: Go 1.5 及以上版本编辑:

As of now, the syntax has changed.截至目前,语法已更改。

On Unix use:在 Unix 上使用:

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

On Windows use:在 Windows 上使用:

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

This is what -X linker flag is for.这就是-X链接器标志的用途。 In your case, you would do在你的情况下,你会做

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

Edit: on Windows this would be编辑:在 Windows 上,这将是

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. Ainer-G 的回答让我找到了正确的地方,但这不是回答问题的完整代码示例。 A couple of changes were required:需要进行一些更改:

  1. Declare the version as var version string将版本声明为var version string
  2. Compile with -X main.version=$VERSION-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"

There is an os.Setenv() function which you can use to set environment variables.有一个os.Setenv()函数可用于设置环境变量。

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).如果您不想通过“手动”执行此操作,您可以为此创建一个工具,该工具将读取VERSION环境变量的当前值并在您的包中生成一个.go源文件,其中包含与上述代码完全相同的代码(除了使用VERSION环境变量的当前值)。 You can run such code generation by issuing the go generate command.您可以通过发出go generate命令来运行此类代码生成。

Read the Generating code blog post for more details about go generate .有关go generate更多详细信息, go generate阅读生成代码博客文章。

Simplest solution, just chain the commands: 最简单的解决方案,只需链接命令:

Instead of: 代替:

VERSION="0.123" go build example.go

Do: 做:

go build example.go && VERSION="0.123" ./example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM