Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions server/routers.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package server

import (
"bytes"
"encoding/json"
"net/http"

Expand Down Expand Up @@ -79,10 +80,14 @@ func NewRouter(routers ...Router) http.Handler {
// EncodeJSONResponse uses the json encoder to write an interface to the http response with an
// optional status code
func EncodeJSONResponse(i interface{}, status int, w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(status)

if err := json.NewEncoder(w).Encode(i); err != nil {
// Encode to buffer first to avoid superfluous WriteHeader call on error
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(i); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(status)
w.Write(buf.Bytes())
}