Is there a way how to set that certain flags are mandatory, or do I have to check for their presence on my own?
相关问题
- Golang mongodb aggregation
- How to flatten out a nested json structure in go
- how to install private repo using glide golang
- Is it possible to pass command-line arguments to @
- How to convert a string to a byte array which is c
相关文章
- Can I run a single test in a suite?
- How to check if a request was cancelled
- Is it possible to implement an interface with unex
- Linux - change the hostname in the CLI
- How to access value of first index of array in Go
- Embedded Interface
- Passing command line arguments to Java via ant bui
- How to represent an array with mixed types
go-flags
lets you declare both required flags and required positional arguments:I agree with this solution but, in my case default values are usually environment values. For example,
And in this case, I want to check if the values are set from invocation (usually local development) or environment var (prod environment).
So with some minor modifications, it worked for my case.
Using flag.VisitAll to check the value of all flags.
Test example in plauground
I like
github.com/jessevdk/go-flags
package to use in CLI. It is providerequired
attribute, to set flag mandatory. Like that:If you have flag path, simply check if *path contains some value
As already mentioned, the
flag
package does not provide this feature directly and usually you can (and should) be able to provide a sensible default. For cases where you only need a small number of explicit arguments (e.g. an input and output filename) you could use positional arguments (e.g. afterflag.Parse()
check thatflag.NArg()==2
and theninput, output := flag.Arg(0), flag.Arg(1)
).If however, you have a case where this isn't sensible; say a few integer flags you want to accept in any order, where any integer value is reasonable, but no default is. Then you can use the
flag.Visit
function to check if the flags you care about were explicitly set or not. I think this is the only way to tell if a flag was explicitly set to it's default value (not counting a customflag.Value
type with aSet
implementation that kept state).For example, perhaps something like:
Playground
This would produce an error if either the "-b" or "-s" flag was not explicitly set.
The
flag
package does not support mandatory or required flags (meaning the flag must be specified explicitly).What you can do is use sensible default values for (all) flags. And if a flag is something like there is no sensible default, check the value at the start of your application and halt with an error message. You should do flag value validation anyway (not just for required flags), so this shouldn't mean any (big) overhead, and this is a good practice in general.