// Homework 45, problem 1: A quotes API. // // Write a read-only JSON API for the quotes below: // GET /api/quotes replies with every quote, as a JSON array. // GET /api/quotes/{id} replies with one quote, 400 for an id that is not a // whole number, and 404 for an id with no quote. // Give the struct tags so that the names in JSON are id, text and author. // Write writeJSON and writeError as in the chapter, and use them for every reply. // // Run with: go run exercises/45/homework/01-quotes-api.go package main import ( "fmt" "net/http" "os" ) // TODO: add struct tags. type quote struct { ID int Text string Author string } // 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"}, } // TODO: write writeJSON and writeError here. func handleListQuotes(w http.ResponseWriter, r *http.Request) { // TODO: write your code here, in place of this placeholder line: fmt.Fprintln(w, "TODO: replace this line") } func handleGetQuote(w http.ResponseWriter, r *http.Request) { // TODO: write your code here, in place of this placeholder line: fmt.Fprintln(w, "TODO: replace this line") } 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) } }