Skip to content

Commit

Permalink
fix: set Content-Type to application/json when responding with json (#64
Browse files Browse the repository at this point in the history
)

* fix: set Content-Type to application/json when responding with json

* test: check for response Content-Type to be application/json
  • Loading branch information
utilyre authored Sep 12, 2023
1 parent 4f22c57 commit 823a9ad
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
6 changes: 5 additions & 1 deletion httperr.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,11 @@ func DefaultErrorHandler(w http.ResponseWriter, err error, status int) {
bts, _ := json.Marshal(errorResponse{
Error: msg,
})
http.Error(w, string(bts), status)

w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
fmt.Fprintln(w, string(bts))
}

// NewWithHandler() wraps a given http.Handler and returns a http.Handler.
Expand Down
10 changes: 10 additions & 0 deletions httperr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ func TestServeHTTPError(t *testing.T) {
t.Fatalf("expected http status %d, got %d", status, resp.StatusCode)
}

contentType := "application/json; charset=utf-8"
if resp.Header.Get("Content-Type") != contentType {
t.Fatalf("expected Content-Type '%s', got '%s'", contentType, resp.Header.Get("Content-Type"))
}

bts, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("got error: %v", err)
Expand All @@ -64,6 +69,11 @@ func TestServeError(t *testing.T) {
t.Fatalf("expected http status %d, got %d", status, resp.StatusCode)
}

contentType := "application/json; charset=utf-8"
if resp.Header.Get("Content-Type") != contentType {
t.Fatalf("expected Content-Type '%s', got '%s'", contentType, resp.Header.Get("Content-Type"))
}

bts, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("got error: %v", err)
Expand Down

0 comments on commit 823a9ad

Please sign in to comment.