Skip to content
Snippets Groups Projects
Commit a174aa61 authored by ale's avatar ale
Browse files

Proper error handling in EncodeJSONResponse

parent 57030d92
Branches
No related tags found
No related merge requests found
......@@ -2,6 +2,7 @@ package serverutil
import (
"encoding/json"
"log"
"net/http"
)
......@@ -28,10 +29,19 @@ func DecodeJSONRequest(w http.ResponseWriter, r *http.Request, obj interface{})
// EncodeJSONResponse writes an application/json response to w.
func EncodeJSONResponse(w http.ResponseWriter, obj interface{}) {
data, err := json.Marshal(obj)
if err != nil {
log.Printf("JSON serialization error: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Expires", "-1")
w.Header().Set("X-Content-Type-Options", "nosniff")
_ = json.NewEncoder(w).Encode(obj)
if _, err = w.Write(data); err != nil {
log.Printf("error writing response: %v", err)
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment