How to reference go-flag IsSet, functional code example needed

412 Views Asked by At

New to Go, and having a basic conceptual problem (I think)...

Trying to use github.com/jessevdk/go-flags and have it mostly working. --help and whatnot are working fine, flags are being passed, etc.

I need to understand if a option was set via a flag or via go-flags parser using the provided default value. It appears go-flags has an "IsSet" function, but I'm clueless how to reference it. Presume:

var opts struct {
    Port int `short:"p" long:"Port" description:"IP port" default:"1111"
}
_, err := flags.Parse(&opts) 

I can reference the value via "opts.Port", but how can I find out if the option was set via a flag or default? Many thanks in advance!

2

There are 2 best solutions below

0
Cassey On

Figured this out:

parser := flags.NewParser(&opts, flags.Default) o := parser.FindOptionByLongName("Port) if o.IsSet() {}

Problme is that IsSet() is true if the flag was used on the command line OR if it was set via the default.

So solved the surface problem of referencing IsSet() but still hunting for an ability to tell which occured, since I want the flag defaults to show in --help.

0
n1ghtm4n4g3r On

Go newbie here as well. IsSetDefault() is also available. (Perhaps, it was added since you asked and answered your question.)