Skip to content

Commit

Permalink
Fixes error content-type according to situations
Browse files Browse the repository at this point in the history
  • Loading branch information
EwenQuim committed Mar 21, 2024
1 parent e12475f commit 1cdf83d
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 5 deletions.
12 changes: 7 additions & 5 deletions serialization.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,16 +92,18 @@ func SendJSON(w http.ResponseWriter, ans any) {
// If the error implements ErrorWithStatus, the status code will be set.
func SendJSONError(w http.ResponseWriter, err error) {
status := http.StatusInternalServerError
errorStatus := HTTPError{
Err: err,
}
var errorStatus ErrorWithStatus
if errors.As(err, &errorStatus) {
status = errorStatus.StatusCode()
}

w.WriteHeader(status)
w.Header().Set("Content-Type", "application/problem+json")
SendJSON(w, errorStatus)
SendJSON(w, err)

var httpError HTTPError
if errors.As(err, &httpError) {
w.Header().Set("Content-Type", "application/problem+json")
}
}

// SendXML sends a XML response.
Expand Down
46 changes: 46 additions & 0 deletions tests_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package fuego

import (
"errors"
"net/http"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/require"
)

// Contains random tests reported on the issues.

func TestContentType(t *testing.T) {
server := NewServer()

t.Run("Sends application/problem+json when return type is HTTPError", func(t *testing.T) {
GetStd(server, "/json-problems", func(w http.ResponseWriter, r *http.Request) {
SendJSONError(w, UnauthorizedError{
Title: "Unauthorized",
})
})

req := httptest.NewRequest("GET", "/json-problems", nil)
w := httptest.NewRecorder()
server.Mux.ServeHTTP(w, req)

require.Equal(t, "application/problem+json", w.Header().Get("Content-Type"))
require.Equal(t, 401, w.Code)
require.Contains(t, w.Body.String(), "Unauthorized")
})

t.Run("Sends application/json when return type is not HTTPError", func(t *testing.T) {
GetStd(server, "/json", func(w http.ResponseWriter, r *http.Request) {
SendJSONError(w, errors.New("error"))
})

req := httptest.NewRequest("GET", "/json", nil)
w := httptest.NewRecorder()
server.Mux.ServeHTTP(w, req)

require.Equal(t, "application/json", w.Header().Get("Content-Type"))
require.Equal(t, 500, w.Code)
require.Equal(t, "{}\n", w.Body.String())
})
}

0 comments on commit 1cdf83d

Please sign in to comment.