// Homework 45, challenge: Update an item. Solution. // // Run from this folder: // cd exercises/45/homework/solutions/04-update-items // go run . // Run its tests with: go test -v package main import ( "encoding/json" "errors" "fmt" "io" "net/http" "os" "strconv" "strings" "unicode/utf8" ) const dataFile = "items.json" const maxBodyBytes = 4096 const maxNameLength = 50 const maxQuantity = 1000 // store is shared by every handler. main opens it before the server starts. var store *itemStore // itemInput is what a client sends to create an item. It has no ID, because // the server chooses the ID. type itemInput struct { Name string `json:"name"` Quantity int `json:"quantity"` } // 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.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) } // writeError sends {"error": message} with the given status. func writeError(w http.ResponseWriter, status int, message string) { writeJSON(w, status, errorReply{Error: message}) } // readJSON decodes the request body into dst. It allows one JSON value of // at most maxBodyBytes, with no fields that dst does not have. 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 } // checkInput returns an error that the client can read, or nil. func checkInput(input itemInput) error { if input.Name == "" { return errors.New("the name is empty") } if utf8.RuneCountInString(input.Name) > maxNameLength { return fmt.Errorf("the name can have at most %d characters", maxNameLength) } if input.Quantity < 1 || input.Quantity > maxQuantity { return fmt.Errorf("the quantity must be from 1 to %d", maxQuantity) } return nil } // readID reads the {id} part of the path. On failure it has already replied. func readID(w http.ResponseWriter, r *http.Request) (int, bool) { id, err := strconv.Atoi(r.PathValue("id")) if err != nil { writeError(w, http.StatusBadRequest, "the id must be a whole number") return 0, false } return id, true } func handleListItems(w http.ResponseWriter, r *http.Request) { items := store.All() search := strings.ToLower(r.URL.Query().Get("q")) if search != "" { found := []item{} for _, it := range items { if strings.Contains(strings.ToLower(it.Name), search) { found = append(found, it) } } items = found } writeJSON(w, http.StatusOK, items) } func handleGetItem(w http.ResponseWriter, r *http.Request) { id, ok := readID(w, r) if !ok { return } it, err := store.Get(id) if errors.Is(err, errNotFound) { writeError(w, http.StatusNotFound, fmt.Sprintf("no item has the id %d", id)) return } if err != nil { fmt.Println("Get error:", err) writeError(w, http.StatusInternalServerError, "the item could not be read") return } writeJSON(w, http.StatusOK, it) } func handleCreateItem(w http.ResponseWriter, r *http.Request) { var input itemInput err := readJSON(w, r, &input) var tooBig *http.MaxBytesError if errors.As(err, &tooBig) { writeError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("the body can be at most %d bytes", tooBig.Limit)) return } if err != nil { writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error()) return } input.Name = strings.TrimSpace(input.Name) err = checkInput(input) if err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } it, err := store.Add(input.Name, input.Quantity) if err != nil { fmt.Println("Save error:", err) writeError(w, http.StatusInternalServerError, "the item could not be saved") return } w.Header().Set("Location", fmt.Sprintf("/api/items/%d", it.ID)) writeJSON(w, http.StatusCreated, it) } func handleDeleteItem(w http.ResponseWriter, r *http.Request) { id, ok := readID(w, r) if !ok { return } err := store.Delete(id) if errors.Is(err, errNotFound) { writeError(w, http.StatusNotFound, fmt.Sprintf("no item has the id %d", id)) return } if err != nil { fmt.Println("Save error:", err) writeError(w, http.StatusInternalServerError, "the item could not be deleted") return } w.WriteHeader(http.StatusNoContent) } func handleUpdateItem(w http.ResponseWriter, r *http.Request) { id, ok := readID(w, r) if !ok { return } var input itemInput err := readJSON(w, r, &input) var tooBig *http.MaxBytesError if errors.As(err, &tooBig) { writeError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("the body can be at most %d bytes", tooBig.Limit)) return } if err != nil { writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error()) return } input.Name = strings.TrimSpace(input.Name) err = checkInput(input) if err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } updated, err := store.Update(id, input.Name, input.Quantity) if errors.Is(err, errNotFound) { writeError(w, http.StatusNotFound, fmt.Sprintf("no item has the id %d", id)) return } if err != nil { fmt.Println("Save error:", err) writeError(w, http.StatusInternalServerError, "the item could not be saved") return } writeJSON(w, http.StatusOK, updated) } // routes connects every pattern to its handler. func routes() *http.ServeMux { mux := http.NewServeMux() mux.HandleFunc("GET /api/items", handleListItems) mux.HandleFunc("GET /api/items/{id}", handleGetItem) mux.HandleFunc("POST /api/items", handleCreateItem) mux.HandleFunc("PUT /api/items/{id}", handleUpdateItem) mux.HandleFunc("DELETE /api/items/{id}", handleDeleteItem) return mux } func main() { s, err := openItemStore(dataFile) if err != nil { fmt.Fprintln(os.Stderr, "Could not load the items:", err) os.Exit(1) } store = s 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) } }