How to define and parse command-line flags with custom usage messages in Go?

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:

  1. Import the flag package:
import "flag"
  1. Define the flags you want to parse. You can use the 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") }
  1. Set a custom usage message by assigning your desired message to 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) } }
  1. Parse the command-line flags using flag.Parse().
func main() { flag.Parse() // Your command-line flag processing logic here }
  1. In case of an error or if the required flags are not provided, you can print the custom usage message using 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.