dongliao3450 2015-02-11 16:15
浏览 46
已采纳

Golang将环境​​变量编译为二进制

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
  • 写回答

4条回答 默认 最新

  • doulin2555 2015-02-11 17:06
    关注

    Go 1.5 and above edit:

    As of now, the syntax has changed. Use

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

    on Linux, and 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么