user17561141
user17561141

Reputation: 31

How to create flag with or without argument in golang using cobra

As I'm new to golang I want to create flag using cobra package : Currently my flag is working for below condition :

cmd.Flags().StringVarP(&flag, "flag", "f", "", "print names")
cmd -f "value"
cmd

but if I'm using

cmd -flag 

then it is showing below error flag needs an argument: 'f' in -f

In this case how to handle the situation as I want to all 3 conditions to work?

Upvotes: 1

Views: 4268

Answers (1)

Ashutosh Singh
Ashutosh Singh

Reputation: 1047

I created a sample program for your scenario by setting no option default values for flags using Cobra. Please refer this link

OR

You can also refer this link for other scenarios

package main

import (
    "fmt"

    "github.com/spf13/cobra"
)

func main() {

    var rootCmd = &cobra.Command{}
    var flag string
    rootCmd.Flags().StringVarP(&flag, "flag", "f", "yep", "times to echo the input")
    rootCmd.Flags().Lookup("flag").NoOptDefVal = "user"  //use this line
    //rootCmd.Execute()
    err := rootCmd.Execute()
    if err != nil {
        fmt.Println("Error :", err)
    }
    fmt.Println("Output :", flag)
}

Output:

D:\cobra>go run main.go rootCmd --flag
Output : user

D:\cobra>go run main.go rootCmd --flag=ms
Output : ms

D:\cobra>go run main.go rootCmd          
Output : yep

Upvotes: 4

Related Questions