-2

I created a small Go application with the https://github.com/spf13/cobra library.

I created a new flag, -t or --token, and when I pass this argument I want the application to print it.

This is what I did:

func init() {
    fmt.Println("[*] Inside init()")
    var token string
    rootCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "Service account Token (JWT) to insert")
    fmt.Println(token)
}  

But it doesn't print it when I run the application like that:

.\consoleplay.exe --token "hello.token"  

How can I print the value of the flags.

E235
  • 11,560
  • 24
  • 91
  • 141

1 Answers1

3

You can't print the value of token in init() function as the init() function executes in run time when the package is called for the first time. The value is not yet assigned.

So, you have to declare the variable globally and use it in the Run method of the rootCmd command.

var token string

var rootCmd = &cobra.Command{
    Use:    "consoleplay",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println(token)
    },
}

func init() {
    rootCmd.Flags().StringVarP(&token, "token", "t", "", "usage")
}
Masudur Rahman
  • 1,585
  • 8
  • 16
  • It does not execute at compile time. Nothing executes at compile time. It executes at runtime, but before `main` executes. https://golang.org/ref/spec#Program_initialization_and_execution – Adrian Jul 24 '19 at 13:11