DEV Community

Cover image for Versioning binaries in Go
Gustavo Castillo
Gustavo Castillo

Posted on

Versioning binaries in Go


In this article we will learn how to add a version to our binaries in Go using a Makefile file and a third party package to print our logo in ASCII code.

Having a version in our binaries is very important since with it, we could know which version of our application we are running on production, in addition our users could report errors for specific versions and thus be able to fix them.

Makefile to create the binary add version, and build time

# Get version from git hash
git_hash := $(shell git rev-parse --short HEAD || echo 'development')

# Get current date
current_time = $(shell date +"%Y-%m-%d:T%H:%M:%S")

# Add linker flags
linker_flags = '-s -X main.buildTime=${current_time} -X main.version=${git_hash}'

# Build binaries for current OS and Linux
    @echo "Building binaries..."
    go build -ldflags=${linker_flags} -o=./bin/binver ./main.go
    GOOS=linux GOARCH=amd64 go build -ldflags=${linker_flags} -o=./bin/linux_amd64/binver ./main.go
Enter fullscreen mode Exit fullscreen mode

After this we will only need to execute the make build command from our terminal to create the binary with its respective version and build time.

Create the main file in Go

package main

import (


var (
    buildTime string
    version   string

const binverFigletStr = `
_     _
| |__ (_)_ ____   _____ _ __
| '_ \| | '_ \ \ / / _ \ '__|
| |_) | | | | \ V /  __/ |
|_.__/|_|_| |_|\_/ \___|_|


func printASCIIArt() {
    binverLogo := aec.LightGreenF.Apply(binverFigletStr)

func main() {
    displayVersion := flag.Bool("version", false, "Display version and exit")


    if *displayVersion {
        fmt.Printf("Version:\t%s\n", version)
        fmt.Printf("Build time:\t%s\n", buildTime)
Enter fullscreen mode Exit fullscreen mode

Repository and video

If you want to see the complete code or the video where I explain how to do it step by step I leave you here the links:

Top comments (3)

dylannorthrup profile image

I know this isn't what you wrote about, but thank you for the pointer to . I've been trying to find a simple way to output ANSI escape codes and this looks like it should fit the bill. Thanks!

yoursunny profile image
Junxiao Shi

I used to have this, but I'm told that including build time goes against reproducible builds.
Now I switched to use the commit time as seen in git history:
I even added Go code so that the version is printed in the same format as Go modules would.

gcdcoder profile image
Gustavo Castillo

Nice! I'll take a look, thanks for sharing.