Читать книгу Practical Go - Amit Saha - Страница 45
Listing 1.7: Greeter program with user interface updates
Оглавление// chap1/flag-improvements/main.go package main import ( "bufio" "errors" "flag" "fmt" "io" "os" ) type config struct { numTimes int name string } var errInvalidPosArgSpecified = errors.New("More than one positional argument specified") // TODO Insert definition of getName() as Listing 1.5 // TODO Insert definition of greetUser() as above // TODO Insert updated definition of runCmd() as above // TODO Insert definition of validateArgs as Listing 1.5 // TODO Insert definition of parseArgs() as above func main() { c, err := parseArgs(os.Stderr, os.Args[1:]) if err != nil { if errors.Is(err, errInvalidPosArgSpecified) { fmt.Fprintln(os.Stdout, err) } os.Exit(1) } err = validateArgs(c) if err != nil { fmt.Fprintln(os.Stdout, err) os.Exit(1) } err = runCmd(os.Stdin, os.Stdout, c) if err != nil { fmt.Fprintln(os.Stdout, err) os.Exit(1) } }
Create a new directory, chap1/flag-improvements/
, and initialize a module inside it:
$ mkdir -p chap1/flag-improvements $ cd chap1/flag-improvements $ go mod init github.com/username/flag-improvements
Next, save Listing 1.7 as main.go
. Build it as follows:
$ go build -o application
Run the built application code with -help
, and you will see the custom usage message:
$ ./application -help A greeter application which prints the name you entered a specified number of times. Usage of greeter: <options> [name] Options: -n int Number of times to greet
Now let's specify a name as a positional argument:
$ ./application -n 1 "Jane Doe" Nice to meet you Jane Doe
Next let's specify a bad input—a string as value to the -n
option:
$ ./flag-improvements -n a "Jane Doe" invalid value "a" for flag -n: parse error A greeter application which prints the name you entered a specified number of times. Usage of greeter: <options> [name] Options: -n int Number of times to greet
Two points are worth noting here:
The error is displayed only once now instead of being displayed twice.
Our custom usage is displayed instead of the default.
Try a few input combinations before moving on to updating the unit tests.