1package api2 3import (4 "context"5 "encoding/json"6 "errors"7 "net/http"8 "strconv"9)10 11var ErrNotFound = errors.New("not found")12 13type User struct {14 ID int64 `json:"id"`15 Name string `json:"name"`16}17 18type UserStore interface {19 User(ctx context.Context, id int64) (User, error)20}21 22type Handler struct{ Store UserStore }23 24func (h *Handler) Routes() http.Handler {25 mux := http.NewServeMux()26 mux.HandleFunc("GET /users/{id}", h.getUser)27 return mux28}29 30func (h *Handler) getUser(w http.ResponseWriter, r *http.Request) {31 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)32 if err != nil || id <= 0 {33 http.Error(w, "bad id", http.StatusBadRequest)34 return35 }36 u, err := h.Store.User(r.Context(), id)37 switch {38 case errors.Is(err, ErrNotFound):39 http.Error(w, "user not found", http.StatusNotFound)40 return41 case err != nil:42 http.Error(w, "internal error", http.StatusInternalServerError)43 return44 }45 w.Header().Set("Content-Type", "application/json")46 _ = json.NewEncoder(w).Encode(u)47}