3
0

Properly handle/write response headers

This commit is contained in:
Denis Arh
2020-11-27 18:59:07 +01:00
parent ec614f8ebc
commit 2586fb9c23
2 changed files with 5 additions and 4 deletions

View File

@@ -76,11 +76,13 @@ func encode(w http.ResponseWriter, r *http.Request, payload interface{}) {
case *successWrap:
// main key is "success"
w.Header().Add("Content-Type", "application/json")
if err = enc.Encode(c); err != nil {
err = fmt.Errorf("failed to encode response: %w", err)
}
default:
w.Header().Add("Content-Type", "application/json")
// main key is "response"
aux := struct {
Response interface{} `json:"response"`
@@ -97,9 +99,8 @@ func encode(w http.ResponseWriter, r *http.Request, payload interface{}) {
}
errors.ServeHTTP(w, r, err, !DebugFromContext(r.Context()))
return
}
w.Header().Set("Content-Type", "application/json")
}
// Send handles first non-nil (and non-empty) payload and encodes it or it's results (when fn)

View File

@@ -29,11 +29,10 @@ func ServeHTTP(w http.ResponseWriter, r *http.Request, err error, mask bool) {
// code = e.kind.httpStatus()
//}
w.WriteHeader(code)
if !mask && !acceptsJson {
// Prettify error for plain text debug output
w.Header().Set("Content-Type", "plain/text")
w.WriteHeader(code)
writeHttpPlain(w, err)
fmt.Fprintln(w, "Note: you are seeing this because system is running in development mode")
fmt.Fprintln(w, "and HTTP request is made without \"Accept: .../json\" headers")
@@ -41,6 +40,7 @@ func ServeHTTP(w http.ResponseWriter, r *http.Request, err error, mask bool) {
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
writeHttpJSON(w, err, mask)
}