// Homework 45, problem 2: A temperature API. // // POST /api/convert takes a body like {"celsius": 21.5} and replies with // {"celsius": 21.5, "fahrenheit": 70.7}, rounded to one decimal place. // Decode strictly: at most 1024 bytes, no unknown fields, one JSON object. // Reply with status 400 and {"error": "..."} when: // - the body is not valid JSON, or has a field other than celsius, // - celsius is missing (hint: a *float64 field is nil when it is missing), // - celsius is below -273.15, the coldest temperature there is. // // Run with: go run exercises/45/homework/02-convert-api.go package main import ( "fmt" "net/http" "os" ) // TODO: add a struct for the request and one for the reply, with tags. // TODO: write writeJSON, writeError and readJSON here. func handleConvert(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("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) } }