How to make your Go program print its version

Since version 1.12 Go includes runtime/debug.BuildInfo type which represents build information read from the running binary.

package main

import (
    "flag"
    "fmt"
    "runtime/debug"
)

func main() {
    var v bool
    flag.BoolVar(&v, "v", false, "show version and exit")
    flag.Parse()
    if v {
        version := "unknown"
        if info, ok := debug.ReadBuildInfo(); ok {
            version = info.Main.Version
        }
        fmt.Println("version:", version)
        return
    }
    fmt.Println("running program")
}