Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

go-flag

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!

like image 490
Cassey Avatar asked Jul 20 '26 06:07

Cassey


1 Answers

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.

like image 76
Cassey Avatar answered Jul 21 '26 23:07

Cassey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!