// Chapter 46 example: a command-line client for the Chapter 45 items API. // Start the Chapter 45 server first, in another terminal. // // Run from this folder: // cd exercises/46/05-items-client // go run . list // go run . add Rice 2 // go run . delete 1 // Run its tests with: go test -v package main import ( "context" "errors" "flag" "fmt" "os" "os/signal" "strconv" ) func usage() { fmt.Fprintln(os.Stderr, "Usage:") fmt.Fprintln(os.Stderr, " go run . [-server URL] list") fmt.Fprintln(os.Stderr, " go run . [-server URL] add NAME QUANTITY") fmt.Fprintln(os.Stderr, " go run . [-server URL] delete ID") flag.PrintDefaults() } // errUsage means the command line was wrong, so main shows the usage. var errUsage = errors.New("wrong usage") // run does the work, and returns an error for main to print. func run(ctx context.Context, client *apiClient, args []string) error { if len(args) == 0 { return errUsage } switch args[0] { case "list": items, err := client.List(ctx) if err != nil { return err } if len(items) == 0 { fmt.Println("The list is empty.") } for _, it := range items { fmt.Printf("%3d %-20s %3d\n", it.ID, it.Name, it.Quantity) } return nil case "add": if len(args) != 3 { return errUsage } quantity, err := strconv.Atoi(args[2]) if err != nil { return fmt.Errorf("the quantity %q is not a whole number", args[2]) } created, err := client.Add(ctx, args[1], quantity) if err != nil { return err } fmt.Printf("Added %s with id %d.\n", created.Name, created.ID) return nil case "delete": if len(args) != 2 { return errUsage } id, err := strconv.Atoi(args[1]) if err != nil { return fmt.Errorf("the id %q is not a whole number", args[1]) } err = client.Delete(ctx, id) if err != nil { return err } fmt.Printf("Deleted item %d.\n", id) return nil } return errUsage } func main() { server := flag.String("server", "http://localhost:8080", "address of the items server") flag.Usage = usage flag.Parse() // Ctrl+C cancels a request that is still waiting, as in Chapter 39. ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() err := run(ctx, newAPIClient(*server), flag.Args()) if errors.Is(err, errUsage) { usage() stop() os.Exit(2) } if err != nil { fmt.Fprintln(os.Stderr, "Error:", err) stop() os.Exit(1) } }