Search code examples
gogo-cobra

Failed to get flag value


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.


Solution

  • 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")
    }