Skip to content

Commit

Permalink
fix: content type header is not json
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelsih committed Jul 20, 2023
1 parent abbc331 commit 2b408e5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
6 changes: 3 additions & 3 deletions httpwr.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ type ErrorHandler func(w http.ResponseWriter, status int, err error)
// DefaultErrorHandler is the default error handler.
// It converts the error to JSON and prints writes it to the response.
func DefaultErrorHandler(w http.ResponseWriter, status int, err error) {
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)

_ = json.NewEncoder(w).Encode(errorResponse{
Status: status,
Expand All @@ -96,8 +96,8 @@ func DefaultErrorHandler(w http.ResponseWriter, status int, err error) {
// OK converts the status and message to JSON and sends it to user.
// Also, it will write the header based on the status.
func OK(w http.ResponseWriter, status int, msg string) error {
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)

type r struct {
Status int `json:"status"`
Expand All @@ -115,8 +115,8 @@ func OK(w http.ResponseWriter, status int, msg string) error {
// OK converts the status, message and custom data you want to JSON.
// Also, it will write the header based on the status.
func OKWithData[T any](w http.ResponseWriter, status int, msg string, data T) error {
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)

type r struct {
Status int `json:"status"`
Expand Down
26 changes: 26 additions & 0 deletions httpwr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,32 @@ func TestHandlerFnWithError(t *testing.T) {
}
}

func TestHeaderJSON(t *testing.T) {
req := httptest.NewRequest("GET", "/json", nil)
w := httptest.NewRecorder()
status := http.StatusOK
msg := "something"
HandlerFn(func(w http.ResponseWriter, r *http.Request) error {
return OK(w, status, msg)
}).ServeHTTP(w, req)
resp := w.Result()
if resp.StatusCode != status {
t.Fatalf("expected http status %d, got %d", status, resp.StatusCode)
}

if resp.Header.Get("Content-Type") != "application/json" {
t.Fatalf("expected application/json, got %s", resp.Header.Get("Content-Type"))
}

bts, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("got error: %v", err)
}
if !strings.Contains(string(bts), msg) {
t.Fatalf("%q does not contain %q", string(bts), msg)
}
}

func TestHandlerFnWithUnknownError(t *testing.T) {
req := httptest.NewRequest("GET", "/hf", nil)
w := httptest.NewRecorder()
Expand Down

0 comments on commit 2b408e5

Please sign in to comment.