// Chapter 46 example: sending JSON with POST, and reading the server's error. // Start the Chapter 45 server first, in another terminal. // Run with: go run exercises/46/03-add-item.go -name Rice -quantity 2 package main import ( "bytes" "context" "encoding/json" "errors" "flag" "fmt" "net/http" "os" "time" ) type item struct { ID int `json:"id"` Name string `json:"name"` Quantity int `json:"quantity"` } type itemInput struct { Name string `json:"name"` Quantity int `json:"quantity"` } // errorReply is the body that the server sends with an error status. type errorReply struct { Error string `json:"error"` } // apiError is a reply from the server that was not a success. type apiError struct { Status int Message string } func (e *apiError) Error() string { return fmt.Sprintf("the server replied %d: %s", e.Status, e.Message) } // readAPIError turns an error response into an *apiError. If the body is not // the JSON the server usually sends, the status text is used instead. func readAPIError(response *http.Response) error { var reply errorReply err := json.NewDecoder(response.Body).Decode(&reply) if err != nil || reply.Error == "" { return &apiError{Status: response.StatusCode, Message: http.StatusText(response.StatusCode)} } return &apiError{Status: response.StatusCode, Message: reply.Error} } func addItem(ctx context.Context, client *http.Client, server string, input itemInput) (item, error) { body, err := json.Marshal(input) if err != nil { return item{}, fmt.Errorf("add item: %w", err) } request, err := http.NewRequestWithContext(ctx, "POST", server+"/api/items", bytes.NewReader(body)) if err != nil { return item{}, fmt.Errorf("add item: %w", err) } request.Header.Set("Content-Type", "application/json") response, err := client.Do(request) if err != nil { return item{}, fmt.Errorf("add item: %w", err) } defer response.Body.Close() if response.StatusCode != http.StatusCreated { return item{}, fmt.Errorf("add item: %w", readAPIError(response)) } var created item err = json.NewDecoder(response.Body).Decode(&created) if err != nil { return item{}, fmt.Errorf("add item: %w", err) } return created, nil } func main() { server := flag.String("server", "http://localhost:8080", "address of the items server") name := flag.String("name", "", "name of the item") quantity := flag.Int("quantity", 1, "how many to buy") flag.Parse() client := &http.Client{Timeout: 10 * time.Second} input := itemInput{Name: *name, Quantity: *quantity} created, err := addItem(context.Background(), client, *server, input) var refused *apiError if errors.As(err, &refused) && refused.Status == http.StatusBadRequest { fmt.Fprintln(os.Stderr, "The server did not accept the item:", refused.Message) os.Exit(1) } if err != nil { fmt.Fprintln(os.Stderr, "Error:", err) os.Exit(1) } fmt.Printf("Added %s (quantity %d) with id %d.\n", created.Name, created.Quantity, created.ID) }