package main import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "strings" "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) } // apiClient talks to the items server at baseURL. type apiClient struct { baseURL string httpClient *http.Client } func newAPIClient(baseURL string) *apiClient { return &apiClient{ baseURL: strings.TrimSuffix(baseURL, "/"), httpClient: &http.Client{Timeout: 10 * time.Second}, } } // do sends a request to path. If input is not nil, it is sent as JSON. The // reply must have the status want, or do returns an *apiError. If output is // not nil, the reply's JSON is decoded into it. func (c *apiClient) do(ctx context.Context, method string, path string, input any, want int, output any) error { var body io.Reader if input != nil { data, err := json.Marshal(input) if err != nil { return err } body = bytes.NewReader(data) } request, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body) if err != nil { return err } if input != nil { request.Header.Set("Content-Type", "application/json") } response, err := c.httpClient.Do(request) if err != nil { return err } defer response.Body.Close() if response.StatusCode != want { 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} } if output != nil { err = json.NewDecoder(response.Body).Decode(output) if err != nil { return fmt.Errorf("the reply is not valid JSON: %w", err) } } return nil } // List returns every item. func (c *apiClient) List(ctx context.Context) ([]item, error) { var items []item err := c.do(ctx, "GET", "/api/items", nil, http.StatusOK, &items) if err != nil { return nil, fmt.Errorf("list items: %w", err) } return items, nil } // Add creates an item and returns it with the ID the server gave it. func (c *apiClient) Add(ctx context.Context, name string, quantity int) (item, error) { var created item input := itemInput{Name: name, Quantity: quantity} err := c.do(ctx, "POST", "/api/items", input, http.StatusCreated, &created) if err != nil { return item{}, fmt.Errorf("add item: %w", err) } return created, nil } // Get returns the item with this ID. func (c *apiClient) Get(ctx context.Context, id int) (item, error) { // TODO: write this method, following List and Delete. return item{}, errors.New("TODO: Get is not written yet") } // Delete removes the item with this ID. func (c *apiClient) Delete(ctx context.Context, id int) error { path := fmt.Sprintf("/api/items/%d", id) err := c.do(ctx, "DELETE", path, nil, http.StatusNoContent, nil) if err != nil { return fmt.Errorf("delete item %d: %w", id, err) } return nil }