Home >Backend Development >Golang >How to Embed Git Revision in Go Binaries Without Modifying Source Code?

How to Embed Git Revision in Go Binaries Without Modifying Source Code?

DDD
DDDOriginal
2024-10-29 11:05:29389browse

How to Embed Git Revision in Go Binaries Without Modifying Source Code?

Adding Git Revision to Binary Builds in Go

A common need in software development is to track the origin of binary executables. This is particularly useful for troubleshooting and establishing the source version from which a binary was built. In Go, it may seem intuitive to add the revision number directly to the source code, but this approach raises concerns about altering the source.

Instead, consider incorporating the git revision during the build process. This approach ensures that the binary reflects the revision used in its creation without modifying the source code.

Building Binaries with Git Revision

To achieve this, utilize the git rev-parse --short HEAD command to retrieve the shortened revision hash. Next, assign this value to a variable named $VERSION in a shell script.

Within your Go source code, declare a version variable within the main package. This variable should have a string data type.

Finally, during the build process, execute the following command to embed the version information into the binary:

#!/bin/sh
VERSION=`git rev-parse --short HEAD`
go build -ldflags "-X main.version=$VERSION"  myfile.go

By executing the command during the build, you can dynamically embed the git revision into the binary without altering the source code. To access the revision information, simply retrieve the value of the version variable in your Go program.

The above is the detailed content of How to Embed Git Revision in Go Binaries Without Modifying Source Code?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn