Go Application Versioning: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(4 intermediate revisions by the same user not shown)
Line 9: Line 9:
=Pass the Version Information as a Linker Argument=
=Pass the Version Information as a Linker Argument=
<syntaxhighlight lang='make'>
<syntaxhighlight lang='make'>
version = $(shell)
version = $(shell $(CURDIR)/scripts/get-version.sh)
 
...
 
build: ...
@go build -ldflags="-X 'example.com/myapp/internal/version.Version=$(version)'" ...
</syntaxhighlight>
 
The <code>go build</code> command passes dynamically-generated version information to the linker. For more details, see: {{Internal|Go_build#-ldflags|<tt>go build -ldflags</tt>}}
 
=Write a Dedicated <code>version</code> Package=
 
The <code>version</code> will contain the <code>Version</code> variable whose value will be replaced at linking time with the actual build value:
 
<syntaxhighlight lang='go'>
package version
 
var Version = "will be updated during linking"
</syntaxhighlight>
 
The use of a variable is mandatory. If declared as constant, the value won't be replaced during linking.
 
<syntaxhighlight lang='go'>
func displayVersion() {
fmt.Printf("%v\n", version.Version)
}
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 23:36, 1 March 2024

External

Internal

Overview

Write an Authoritative Source of Version Information Script

The version information for a build should be generate in just one place. A shell script is probably the most versatile. Write a script that generate the version label at stdout and name it ${PROJECT_DIR}/scripts/get-version.sh.

Pass the Version Information as a Linker Argument

version = $(shell $(CURDIR)/scripts/get-version.sh)

...

build: ...
	@go build -ldflags="-X 'example.com/myapp/internal/version.Version=$(version)'" ...

The go build command passes dynamically-generated version information to the linker. For more details, see:

go build -ldflags

Write a Dedicated version Package

The version will contain the Version variable whose value will be replaced at linking time with the actual build value:

package version

var Version = "will be updated during linking"

The use of a variable is mandatory. If declared as constant, the value won't be replaced during linking.

func displayVersion() {
	fmt.Printf("%v\n", version.Version)
}