Skip to content

Commit eb200cb

Browse files
Fixed the error handling on the response.
1 parent 1bddbd5 commit eb200cb

1 file changed

Lines changed: 16 additions & 6 deletions

File tree

‎chapter9/listing04/example04.go‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ package main
33

44
import (
55
"encoding/json"
6+
"fmt"
67
"log"
78
"net/http"
9+
"strconv"
810
)
911

1012
// main is the entry point for the application.
@@ -30,21 +32,29 @@ func SendJSON(rw http.ResponseWriter, r *http.Request) {
3032
Email: "bill@ardanstudios.com",
3133
}
3234

33-
rw.Header().Set("Content-Type", "application/json")
34-
rw.WriteHeader(200)
35-
36-
if err := json.NewEncoder(rw).Encode(u); err != nil {
37-
log.Panic(err)
35+
data, err := json.Marshal(&u)
36+
if err != nil {
37+
// We want this error condition to panic so we get a stack trace. This should
38+
// never happen. The http package will catch the panic and provide logging
39+
// and return a 500 back to the caller.
40+
log.Panic("Unable to unmatshal response", err)
3841
}
3942

43+
datalen := len(data) + 1 // account for trailing LF
44+
h := rw.Header()
45+
h.Set("Content-Type", "application/json")
46+
h.Set("Content-Length", strconv.Itoa(datalen))
47+
rw.WriteHeader(200)
48+
fmt.Fprintf(rw, "%s\n", data)
49+
4050
LogResponse(&u)
4151
}
4252

4353
// LogResponse is used to write the response to the log.
4454
func LogResponse(v interface{}) {
4555
d, err := json.MarshalIndent(v, "", " ")
4656
if err != nil {
47-
log.Println("Unable to Marshal Response", err)
57+
log.Println("Unable to marshal response", err)
4858
return
4959
}
5060

0 commit comments

Comments
 (0)