Tracking response codes

Report a typo

Sometimes servers misbehave or users make bad request, so you can receive a response code with some error status, and you need to retry your request to get a successful response.

Write a program that will make GET HTTP requests to http://127.0.0.1:8080/api until the server returns a successful status code (2**), and then print the body of the response as a string.

Write a program in Go
package main

import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)

func main() {
// Write your code here
}

// DO NOT MODIFY the contents of the init() or must() functions!
func init() {
const timeout = 5 * time.Second

var input []struct {
Code int `json:"code"`
Body string `json:"body"`
}

must(json.NewDecoder(os.Stdin).Decode(&input))

go func() {
var count int
http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
response := input[count%len(input)]
w.WriteHeader(response.Code)
if _, err := w.Write([]byte(response.Body)); err != nil {
panic(err)
}
count++
})
___

Create a free account to access the full topic