英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论