How to set package variable using -ldflags -X in Golang build

前端 未结 2 1397
伪装坚强ぢ
伪装坚强ぢ 2021-02-02 12:33

I am creating an app using Go 1.9.2 and I am trying to add a version string variable to it using the ldflags -X options during the build.

I\'ve managed to s

相关标签:
2条回答
  • 2021-02-02 13:12

    Quoting from doc of Command link:

    -X importpath.name=value
        Set the value of the string variable in importpath named name to value.
        Note that before Go 1.5 this option took two separate arguments.
        Now it takes one argument split on the first = sign.
    

    So it can be used for any package, not just for the main package. But you must specify the full import path, not just the package name.

    E.g. if your config package is located at $GOPATH/src/my/package/config, then use the following command:

    go build -ldflags "-X my/package/config.Version=1.0.0" -o $(MY_BIN) $(MY_SRC)
    
    0 讨论(0)
  • 2021-02-02 13:22

    Here's a simple example, hopefully it would clarify and help how to do it easily:

    Create a directory for your application:

    $ mkdir app && cd app
    

    Create a sub directory config:

    $ mkdir config 
    

    Add the following file. it should be under app/config/vars.go:

    package config
    
    var Version string 
    
    var BuildTime string 
    //todo: can add as many as build vars 
    

    In the root app/, add main package main.go:

    package main
    
    import (
        "fmt"
        "app/config"
    )
    
    func main() {
        fmt.Println("build.Version:\t", Version)
        fmt.Println("build.Time:\t", build.BuildTime)
    }
    

    Now it is time to build:

    go build -ldflags "-X 'app/config.Version=0.0.1' -X 'app/config.BuildTime=$(date)'"

    Once it's built, you can run now the app:

    $ ./app 
    Version:     0.0.1
    build.Time:  Sat Jul  4 19:49:19 UTC 2020
    

    Finally, you may need sometimes to explore what does specific app you didn't code yourself provide in ldflags, you can do this by using nm that comes with go tool to list all ldflags.

    Just build the app then use go tool nm to list all linker flags.

    $ go build -o app 
    $ go tool nm ./app 
    

    Still have any questions or anything to be more clarified? please feel free to leave a comment below and I will get back to you as soon as I can.

    0 讨论(0)
提交回复
热议问题