Skip to content

Commit

Permalink
Fixed the error handling on the response.
Browse files Browse the repository at this point in the history
  • Loading branch information
ardan-bkennedy committed May 1, 2015
1 parent 1bddbd5 commit eb200cb
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions chapter9/listing04/example04.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package main

import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
)

// main is the entry point for the application.
Expand All @@ -30,21 +32,29 @@ func SendJSON(rw http.ResponseWriter, r *http.Request) {
Email: "[email protected]",
}

rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(200)

if err := json.NewEncoder(rw).Encode(u); err != nil {
log.Panic(err)
data, err := json.Marshal(&u)
if err != nil {
// We want this error condition to panic so we get a stack trace. This should
// never happen. The http package will catch the panic and provide logging
// and return a 500 back to the caller.
log.Panic("Unable to unmatshal response", err)
}

datalen := len(data) + 1 // account for trailing LF
h := rw.Header()
h.Set("Content-Type", "application/json")
h.Set("Content-Length", strconv.Itoa(datalen))
rw.WriteHeader(200)
fmt.Fprintf(rw, "%s\n", data)

LogResponse(&u)
}

// LogResponse is used to write the response to the log.
func LogResponse(v interface{}) {
d, err := json.MarshalIndent(v, "", " ")
if err != nil {
log.Println("Unable to Marshal Response", err)
log.Println("Unable to marshal response", err)
return
}

Expand Down

0 comments on commit eb200cb

Please sign in to comment.