// Homework 45, problem 2: A temperature API. Solution. // // Run with: go run exercises/45/homework/solutions/02-convert-api.go package main import ( "encoding/json" "errors" "fmt" "io" "math" "net/http" "os" ) const maxBodyBytes = 1024 const absoluteZero = -273.15 // convertRequest uses a pointer, so that a missing celsius is nil and not 0. type convertRequest struct { Celsius *float64 `json:"celsius"` } type convertReply struct { Celsius float64 `json:"celsius"` Fahrenheit float64 `json:"fahrenheit"` } 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 handleConvert(w http.ResponseWriter, r *http.Request) { var input convertRequest err := readJSON(w, r, &input) if err != nil { writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error()) return } if input.Celsius == nil { writeError(w, http.StatusBadRequest, "celsius is missing") return } celsius := *input.Celsius if celsius < absoluteZero { writeError(w, http.StatusBadRequest, "celsius cannot be below -273.15") return } fahrenheit := celsius*9/5 + 32 fahrenheit = math.Round(fahrenheit*10) / 10 writeJSON(w, http.StatusOK, convertReply{Celsius: celsius, Fahrenheit: fahrenheit}) } func main() { http.HandleFunc("POST /api/convert", handleConvert) 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) } }