Shermans's Notes
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Injecting Variables At Build Time

    Full article: https://www.digitalocean.com/community/tutorials/using-ldflags-to-set-version-information-for-go-applications

    TLDR:

    Given some var in a file"

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    
    package main
    
    var (
    	Version = "0.0.1"
    	Commit  = "DEADBEEF"
    )
    
    func main() {
    	fmt.Printf("Version: %s", Version)
    	fmt.Printf("Commit: %s", Commit)
    }
    

    The following will overwrite them at build time (also works with go run)

    1
    
    go build -ldflags="-X 'main.Version=1.0.0' -X 'main.Commit="BEEFDEAD"'"
    

    If you are unsure of the full name of the variable you and run:

    1
    
    go tool nm ./app | grep var_name