// Package web is a small JSON API for scores. package web import ( "encoding/json" "log/slog" "net/http" "scores/internal/score" ) // Store is what this package needs from a store. store.File has these // methods, and so do the fakes in the tests. type Store interface { List() []score.Score Add(sc score.Score) error } // App holds what the handlers need. Make one with New. type App struct { store Store logger *slog.Logger } // New returns an App that uses this store and logger. func New(s Store, logger *slog.Logger) *App { return &App{store: s, logger: logger} } // Handler returns the routes. func (a *App) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /api/scores", a.handleList) mux.HandleFunc("POST /api/scores", a.handleAdd) return mux } func (a *App) handleList(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, a.store.List()) } func (a *App) handleAdd(w http.ResponseWriter, r *http.Request) { var input score.Score err := json.NewDecoder(r.Body).Decode(&input) if err != nil { writeJSON(w, http.StatusBadRequest, errorReply{Error: "invalid JSON"}) return } sc, err := score.New(input.Player, input.Points) if err != nil { writeJSON(w, http.StatusBadRequest, errorReply{Error: err.Error()}) return } err = a.store.Add(sc) if err != nil { a.logger.Error("could not save", "err", err) writeJSON(w, http.StatusInternalServerError, errorReply{Error: "the score could not be saved"}) return } a.logger.Info("score added", "player", sc.Player, "points", sc.Points) writeJSON(w, http.StatusCreated, sc) } // errorReply is the body of every error response. type errorReply struct { Error string `json:"error"` } // writeJSON sends value as JSON with the given status. func writeJSON(w http.ResponseWriter, status int, value any) { data, err := json.Marshal(value) if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) w.Write(data) }