// Homework 46, problem 2: A temperature client. // // Start the temperature server from homework 45 first, in another terminal: // go run exercises/45/homework/solutions/02-convert-api.go // Write toFahrenheit, which sends {"celsius": C} to POST /api/convert and // returns the fahrenheit from the reply. Set the Content-Type header. When the // status is not 200, return an error that holds the status and the server's // message from {"error": "..."}, such as // "convert: the server replied 400: celsius cannot be below -273.15". // // Run with: go run exercises/46/homework/02-convert-client.go package main import ( "context" "errors" "flag" "fmt" "net/http" "time" ) 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 toFahrenheit(ctx context.Context, client *http.Client, server string, celsius float64) (float64, error) { // TODO: write your code here, in place of this placeholder line: return 0, errors.New("TODO: toFahrenheit is not written yet") } func main() { server := flag.String("server", "http://localhost:8080", "address of the temperature server") flag.Parse() client := &http.Client{Timeout: 10 * time.Second} temperatures := []float64{-40, 0, 21.5, 100, -300} for _, celsius := range temperatures { fahrenheit, err := toFahrenheit(context.Background(), client, *server, celsius) if err != nil { fmt.Printf("%6.1f C: %v\n", celsius, err) continue } fmt.Printf("%6.1f C = %6.1f F\n", celsius, fahrenheit) } }