I am making an API Request Tool using go, and want to use the "flag" package.
I have defined a flag using flag.String
but when I enter a flag that does not exist
the program prints "flag provided but not defined: {flag}" (where {flag} is a flag that does not exist.)
My code is:
package main
import "fmt"
import "flag"
import "os"
func main() {
// Set up command-line arguments
apiRequestTool := flag.String("api", "", "")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: TestTestTest\n")
os.Exit(1)
}
flag.Parse()
// Check API URL value
if *apiRequestTool == "" {
fmt.Println("\"api\" Usage: --api [string]")
os.Exit(1)
}
}
Functions like flag.String
and flag.Parse
operate on an exported *flag.FlagSet
singleton named flag.CommandLine
. One way of suppressing all error messages from that flag set consists in diverting its output to a black hole (e.g. at the top of your main function) like this:
flag.CommandLine.SetOutput(io.Discard)
After that, the error message that you perceive as annoying won't get printed:
$ go run main.go --whatever
Usage: TestTestTest
exit status 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With