forked from goinaction/code
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fixed the error handling on the response.
- Loading branch information
1 parent
1bddbd5
commit eb200cb
Showing
1 changed file
with
16 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,8 +3,10 @@ package main | |
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"log" | ||
"net/http" | ||
"strconv" | ||
) | ||
|
||
// main is the entry point for the application. | ||
|
@@ -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 | ||
} | ||
|
||
|