// Homework 45, problem 1: A quotes API. Solution. // // Run with: go run exercises/45/homework/solutions/01-quotes-api.go package main import ( "encoding/json" "fmt" "net/http" "os" "strconv" ) type quote struct { ID int `json:"id"` Text string `json:"text"` Author string `json:"author"` } // The quotes never change, so the handlers can share them with no mutex. var quotes = []quote{ {ID: 1, Text: "Clear is better than clever.", Author: "Rob Pike"}, {ID: 2, Text: "Errors are values.", Author: "Rob Pike"}, {ID: 3, Text: "Don't panic.", Author: "Rob Pike"}, } 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 handleListQuotes(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, quotes) } func handleGetQuote(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(r.PathValue("id")) if err != nil { writeError(w, http.StatusBadRequest, "the id must be a whole number") return } for _, q := range quotes { if q.ID == id { writeJSON(w, http.StatusOK, q) return } } writeError(w, http.StatusNotFound, fmt.Sprintf("no quote has the id %d", id)) } func main() { http.HandleFunc("GET /api/quotes", handleListQuotes) http.HandleFunc("GET /api/quotes/{id}", handleGetQuote) fmt.Println("Server running at http://localhost:8080") fmt.Println("Press Ctrl+C to stop it.") err := http.ListenAndServe("localhost:8080", nil) if err != nil { fmt.Fprintln(os.Stderr, "Server stopped:", err) os.Exit(1) } }