In Go, you can define and parse command-line flags with custom usage messages using the flag
package. Here's how you can do it:
flag
package:import "flag"
flag
package's StringVar
, IntVar
, BoolVar
, etc. functions to define the flag variables.var (
name string
age int
flagUsage = "Usage: your_command -name=<name> -age=<age>"
)
func init() {
flag.StringVar(&name, "name", "", "Your name")
flag.IntVar(&age, "age", 0, "Your age")
}
flag.Usage
. You can set this in the init()
function.func init() {
flag.StringVar(&name, "name", "", "Your name")
flag.IntVar(&age, "age", 0, "Your age")
flag.Usage = func() {
fmt.Fprint(os.Stderr, flagUsage)
}
}
flag.Parse()
.func main() {
flag.Parse()
// Your command-line flag processing logic here
}
flag.Usage()
.func main() {
flag.Parse()
if name == "" || age == 0 {
flag.Usage()
os.Exit(1)
}
// Your command-line flag processing logic here
}
Now, when you run your program without the required flags or with the -h
or --help
flag, it will show your custom usage message.
Here's an example of how you can run the program:
go run your_program.go -name=John -age=25
If you run the program without the required flags or with the -h
or --help
flag, the custom usage message will be displayed.
Note: It's a good practice to call flag.Parse()
in the main function rather than inside the init()
function, so you have more control over when the flags are parsed.