// Homework 45, problem 3: Test a counter API. // // This server is finished. Write the tests in main_test.go. // // Run from this folder: // cd exercises/45/homework/03-test-counter // go run . // Run its tests with: go test -v package main import ( "encoding/json" "errors" "fmt" "io" "net/http" "os" "sync" ) const maxBodyBytes = 1024 // counter is a number that many requests can change safely. type counter struct { mu sync.Mutex // protects value value int } func (c *counter) Value() int { c.mu.Lock() defer c.mu.Unlock() return c.value } // Add adds by, and returns the new value. func (c *counter) Add(by int) int { c.mu.Lock() defer c.mu.Unlock() c.value += by return c.value } // count is shared by every handler. var count = &counter{} type valueReply struct { Value int `json:"value"` } type addRequest struct { By int `json:"by"` } type errorReply struct { Error string `json:"error"` } func writeJSON(w http.ResponseWriter, status int, value any) { data, err := json.MarshalIndent(value, "", " ") if err != nil { fmt.Println("JSON error:", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } data = append(data, '\n') w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) // An error here means the client has gone, so there is no one to tell. w.Write(data) } func writeError(w http.ResponseWriter, status int, message string) { writeJSON(w, status, errorReply{Error: message}) } func readJSON(w http.ResponseWriter, r *http.Request, dst any) error { r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes) decoder := json.NewDecoder(r.Body) decoder.DisallowUnknownFields() err := decoder.Decode(dst) if err != nil { return err } err = decoder.Decode(&struct{}{}) if !errors.Is(err, io.EOF) { return errors.New("the body must hold one JSON object only") } return nil } func handleGetCounter(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, valueReply{Value: count.Value()}) } func handleAdd(w http.ResponseWriter, r *http.Request) { var input addRequest err := readJSON(w, r, &input) if err != nil { writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error()) return } if input.By < 1 || input.By > 100 { writeError(w, http.StatusBadRequest, "by must be from 1 to 100") return } writeJSON(w, http.StatusOK, valueReply{Value: count.Add(input.By)}) } func routes() *http.ServeMux { mux := http.NewServeMux() mux.HandleFunc("GET /api/counter", handleGetCounter) mux.HandleFunc("POST /api/counter/add", handleAdd) return mux } func main() { fmt.Println("Server running at http://localhost:8080") fmt.Println("Press Ctrl+C to stop it.") err := http.ListenAndServe("localhost:8080", routes()) if err != nil { fmt.Fprintln(os.Stderr, "Server stopped:", err) os.Exit(1) } }