var timesFlag int
flag.IntVar(×Flag, "times", 1, "Number of times to print")
flag.Parse()
If I run the program and type in prog -times=abc (<--- not an int)
fmt.Parse spits out this ugly error message on the console:
invalid value "-abc" for flag -times: strconv.ParseInt: parsing "-abc": invalid syntax
Obviously, I can't prevent the user from typing in anything from the command line. The error looks like garbage to the user and needs to look more friendlier. How do I silent this error from going to stderr/stdout and detect there was an error generated?
The flag.CommandLine
variable of type the FlagSet
is used to handle command line arguments if you use the functions of the flag
package which are not methods of the FlagSet
type.
You can set the output (an io.Writer
) where error messages are printed with the FlagSet.SetOutput()
method. You can set a bytes.Buffer
so messages will only end up in a buffer (and not on your console). Note that do not set nil
as that means to print to the standard output (console).
And call FlagSet.Parse()
yourself where you can pass os.Args[1:]
as the arguments to be parsed. FlagSet.Parse()
returns an error
which you can handle yourself.