package main // This is the starter. do and List are finished. The TODOs are in Add, Delete // and Report. import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "time" "expenses/internal/expense" ) // 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 a running "expenses serve" at baseURL. type apiClient struct { baseURL string httpClient *http.Client } func newAPIClient(baseURL string) *apiClient { return &apiClient{ baseURL: 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 fmt.Errorf("could not reach the server (is \"expenses serve\" running?): %w", 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 } // monthQuery returns "?month=..." for a month, or "" for every month. func monthQuery(month string) string { if month == "" { return "" } values := url.Values{} values.Set("month", month) return "?" + values.Encode() } // List returns the expenses of one month, or of every month if month is "". func (c *apiClient) List(ctx context.Context, month string) ([]expense.Expense, error) { var list []expense.Expense err := c.do(ctx, "GET", "/api/expenses"+monthQuery(month), nil, http.StatusOK, &list) if err != nil { return nil, fmt.Errorf("list expenses: %w", err) } return list, nil } // Add sends a new expense, and returns it with the ID the server gave it. func (c *apiClient) Add(ctx context.Context, e expense.Expense) (expense.Expense, error) { // TODO: as List does, but POST e to /api/expenses, want // http.StatusCreated, and decode the reply into an expense.Expense. return expense.Expense{}, errors.New("TODO: Add is not written yet") } // Delete removes the expense with this ID. func (c *apiClient) Delete(ctx context.Context, id int) error { // TODO: send DELETE to /api/expenses/{id}, and want // http.StatusNoContent. There is no body either way, so input and output // are nil. return errors.New("TODO: Delete is not written yet") } // Report returns the totals of one month, or of every month if month is "". func (c *apiClient) Report(ctx context.Context, month string) (expense.Report, error) { // TODO: as List does, but GET /api/report and decode into an // expense.Report. return expense.Report{}, errors.New("TODO: Report is not written yet") }