Is it possible to hide the golang messages? I show you an example:
package main
import (
"flag"
"fmt"
"os"
)
var signal = flag.String("z", "", "")
func main() {
flag.Usage = func() {
fmt.Printf("Usage: kata -z <command>
")
fmt.Printf(" test\tTesting
")
fmt.Printf(" version\tVersion
")
fmt.Println("")
}
flag.Parse()
if len(os.Args) != 3 {
flag.Usage()
os.Exit(1)
}
switch *signal {
case "test":
fmt.Println("testing...")
case "version":
fmt.Println("0.0.1")
default:
fmt.Println("incorrect...")
}
}
This app show to user the next information: https://play.golang.org/p/oYwADdmlAJ
But if I write in the command-line kata -flag
, the system returns: flag needs an argument:
or flag provided but not defined:
and the information that I show you before.
I would like to know if it's possible to hide the golang messages?
P.S.: If you don't understand my question, I can rephrase.
Using the global functions in flag
actually passes through to a global flag.FlagSet
called flag.CommandLine
. Internally, this prints errors to an output, which is stderr by default. You can suppress the messages by setting this explicitly to, for example, ioutil.Discard
:
flag.CommandLine.SetOutput(ioutil.Discard)
flag.Parse()
This will discard all messages output internally by flag.Parse()
. You could also log it to anywhere else you choose by passing in an appropriate io.Writer
.
I have found a solution:
Before:
flag.Parse()
if len(os.Args) != 3 {
flag.Usage()
os.Exit(1)
}
Now:
if len(os.Args) != 3 || os.Args[1] != "-z" {
flag.Usage()
os.Exit(1)
} else {
flag.Parse()
}