Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rid of "flag provided but not defined" when using "flag" package

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)
    }
}
like image 967
Wantyapps Avatar asked Oct 19 '25 08:10

Wantyapps


1 Answers

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
like image 111
jub0bs Avatar answered Oct 20 '25 22:10

jub0bs



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!