// Homework 46, challenge: One item, tested. // // This is the chapter's items client. Add a get command that shows one item: // go run . get 4 // 4: Soap, quantity 3 // Write the client's Get method in client.go, then the get case in run here, // then TestGet and TestGetNotFound in client_test.go. Start the Chapter 45 // items server first, in another terminal, to try the command. // // Run from this folder: // cd exercises/46/homework/04-get-item // go run . get 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] get ID") 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 "get": // TODO: check the arguments, call client.Get, and print the item as // "4: Soap, quantity 3", in place of this placeholder line: return errors.New("TODO: the get command is not written yet") 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) } }