DEV Community

Cover image for Versioning binaries in Go
Gustavo Castillo
Gustavo Castillo

Posted on

Versioning binaries in Go

#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
.PHONY:
build:
    @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 (
    "flag"
    "fmt"
    "os"

    "github.com/morikuni/aec"
)

var (
    buildTime string
    version   string
)

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

`

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

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

    flag.Parse()

    if *displayVersion {
        printASCIIArt()
        fmt.Printf("Version:\t%s\n", version)
        fmt.Printf("Build time:\t%s\n", buildTime)
        os.Exit(0)
    }
}
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)

Collapse
 
dylannorthrup profile image
dylannorthrup

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

Collapse
 
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:
github.com/usnistgov/ndn-dpdk/tree...
I even added Go code so that the version is printed in the same format as Go modules would.

Collapse
 
gcdcoder profile image
Gustavo Castillo

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