Home > Software engineering >  Golang Argparse not picking correct value for multiple flags
Golang Argparse not picking correct value for multiple flags

Time:09-09

I have a golang binary named test. I have two flags -p and -s using golang argparse library. I want user to pass them like below scenarios:

./test -p
./test -s serviceName
./test -p -s serviceName

Means -p should be passed with empty value and -s should be passed with any service name. 1 and 2 are working fine but in third -p flag is taking value "-s". What i want from 3rd is -p should be empty value ("") and -s should be "serviceName". Code:

parser := argparse.NewParser("./test", "Check status/version of test")
parser.DisableHelp()
platformFormatVal := parser.String("p", "platform", &argparse.Options{Required: false, Help: "Print status of platform", Default: "Inplatform"})
serviceFormatVal := parser.String("s", "service", &argparse.Options{Required: false, Help: "Print status of service", Default: "Inservice"})
err := parser.Parse(os.Args)
if err != nil {
        //generic error
    }
platformFormat = *platformFormatVal
serviceFormat = *serviceFormatVal

CodePudding user response:

Haven't used argparse lib, only the standard flag, but according to the docs, you are configuring p as a string argument, while it is actually a boolean flag.

You should configure your arguments similar to this:

    sArg := parser.String("s", ...)
    pArg := parser.Flag("p", ...)

Then you can use it like this:

  if *pArg {
     ...
  }
  • Related