in golang/go-guestbook/src/frontend/main.go [67:113]
func (f *frontendServer) homeHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("received request: %s %s", r.Method, r.URL.Path)
if r.Method != http.MethodGet {
http.Error(w, fmt.Sprintf("only GET requests are supported (got %s)", r.Method), http.StatusMethodNotAllowed)
return
}
if r.URL.Path != "/" {
http.Error(w, "page not found", http.StatusNotFound)
return
}
log.Printf("querying backend for entries")
resp, err := http.Get(fmt.Sprintf("http://%s/messages", f.backendAddr))
if err != nil {
http.Error(w, fmt.Sprintf("querying backend failed: %+v", err), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
http.Error(w, fmt.Sprintf("failed to read response body: %+v", err), http.StatusInternalServerError)
return
}
if resp.StatusCode != http.StatusOK {
http.Error(w, fmt.Sprintf("got status code %d from the backend: %s", resp.StatusCode, string(body)), http.StatusInternalServerError)
return
}
log.Printf("parsing backend response into json")
var v []guestbookEntry
if err := json.Unmarshal(body, &v); err != nil {
log.Printf("WARNING: failed to decode json from the api: %+v input=%q", err, string(body))
http.Error(w,
fmt.Sprintf("could not decode json response from the api: %+v", err),
http.StatusInternalServerError)
return
}
log.Printf("retrieved %d messages from the backend api", len(v))
if err := tpl.ExecuteTemplate(w, "home", map[string]interface{}{
"messages": v,
}); err != nil {
log.Printf("WARNING: failed to render html template: %+v", err)
}
}