Читать книгу Practical Go - Amit Saha - Страница 43

Customizing Usage Message

Оглавление

If you compare Listing 1.5 to Listing 1.1, you will notice that there is no custom usageString specified. This is because the flag package automatically constructs one based on the FlagSet name and the options defined. However, what if you wanted to customize it? You can do so by setting the Usage attribute of the FlagSet object to a function as follows:

fs.Usage = func() { var usageString = ` A greeter application which prints the name you entered a specified number of times. Usage of %s: ` fmt.Fprintf(w, usageString, fs.Name()) fmt.Fprintln(w) fs.PrintDefaults() }

Once we set the Usage attribute of the FlagSet object to a custom function, it is called whenever there is an error parsing the specified options. Note that the preceding function is defined as an anonymous function so that it can access the specified writer object, w, to display the custom usage message. Inside the function, we access the name of the FlagSet using the Name() method. Then we print a new line and call the PrintDefaults() method, which prints the various options that have been defined along with their type and default values. The updated parseArgs() function is as follows:

func parseArgs(w io.Writer, args []string) (config, error) { c := config{} fs := flag.NewFlagSet("greeter", flag.ContinueOnError) fs.SetOutput(w) fs.Usage = func() { var usageString = ` A greeter application which prints the name you entered a specified number of times. Usage of %s: <options> [name]` fmt.Fprintf(w, usageString, fs.Name()) fmt.Fprintln(w) fmt.Fprintln(w, "Options: ") fs.PrintDefaults() } fs.IntVar(&c.numTimes, "n", 0, "Number of times to greet") err := fs.Parse(args) if err != nil { return c, err } if fs.NArg()> 1 { return c, errInvalidPosArgSpecified } if fs.NArg() == 1 { c.name = fs.Arg(0) } return c, nil }

Next, you will implement the final improvement. The greeter program will now allow specifying the name via a positional argument as well. If one is not specified, you will ask for the name interactively.

Practical Go

Подняться наверх