如何在编译时将字符串嵌入到二进制文件中?

huangapple go评论68阅读模式
英文:

How to embed a string in the compiled binary at build time?

问题

我想在编译的二进制文件中嵌入传递给构建过程的信息,这些信息在构建时传递(通常是一个字符串,特别是在我的 CI/CD 执行期间的提交哈希)。

然后,我希望可以使用 fmt.Sprintf("%v", thisEmbeddedString) 简单地显示它。

我原本希望 embed 包可以解决这个问题,但它似乎只适用于文件。

英文:

I would like to embed in the compiled binary information passed to the build process, at build time (typically a string, specifically the commit hash during my CI/CD execution).

I then would like to simply display it with fmt.Sprintf("%v", thisEmbeddedString).

I was hoping for the embed package to be a solution, but it seems to be only for files.

答案1

得分: 3

在你的代码中声明一个变量(在下面的示例中,在main函数中,它将在下一步中设置):

var commit string

在构建中添加一个标志:

go build -ldflags "-X main.commit=$GIT_COMMIT"

然后你可以像平常一样访问这个变量:

log.Info().Msgf("commit → %v", commit)
英文:

Declare a variable in your code (in the example below, in main, it will be set in the next step)

var commit string

Add a flag to the build

go build -ldflags "-X main.commit=$GIT_COMMIT"

You can then access the variable as usual

log.Info().Msgf("commit → %v", commit)

huangapple
  • 本文由 发表于 2022年1月5日 17:50:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/70590805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定