Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes error Content-Type #89

Merged
merged 1 commit into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
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
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())
})
}
Loading