To display usage information for a Go program with defined flags, you can use the flag
package in Go. Here's an example of how you can do it:
flag
package:import "flag"
var (
flag1 = flag.String("flag1", "default value", "description for flag1")
flag2 = flag.Int("flag2", 0, "description for flag2")
// ... define more flags
)
func printUsage() {
flag.PrintDefaults()
}
flag.Parse()
-h
or --help
flag to print the usage information and exit the program:if len(os.Args) > 1 && (os.Args[1] == "-h" || os.Args[1] == "--help") {
printUsage()
os.Exit(0)
}
Now, when you run your program with the -h
or --help
flag, it will display the usage information, including the defined flags and their descriptions.
For example:
$ go run main.go -h
Usage of /tmp/go-build1415292925/b001/exe/main:
-flag1 string
description for flag1 (default "default value")
-flag2 int
description for flag2 (default 0)
...
Note: Make sure to replace main.go
with the actual name of your Go file.