Skip to content

Commit 23bd44f

Browse files
maxatomefredbi
authored andcommitted
fix: Content-Type of 404 & 405 responses
Fixes #372 If a specification contains a default producer Content-Type and at least one route with a specific (and different) producer Content-Type, the Content-Type of 405 and 404 responses was this specific Content-Type. Now the default producer Content-Type is always used. Signed-off-by: Maxime Soulé <[email protected]>
1 parent 078717a commit 23bd44f

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

middleware/router.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,17 @@ func NewRouter(ctx *Context, next http.Handler) http.Handler {
6868
return
6969
}
7070

71+
// Always use the default producer Content-Type for Method not
72+
// allowed and Not found responses
73+
produces := []string{ctx.api.DefaultProduces()}
74+
7175
// Not found, check if it exists in the other methods first
7276
if others := ctx.AllowedMethods(r); len(others) > 0 {
73-
ctx.Respond(rw, r, ctx.analyzer.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others))
77+
ctx.Respond(rw, r, produces, nil, errors.MethodNotAllowed(r.Method, others))
7478
return
7579
}
7680

77-
ctx.Respond(rw, r, ctx.analyzer.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.EscapedPath()))
81+
ctx.Respond(rw, r, produces, nil, errors.NotFound("path %s was not found", r.URL.EscapedPath()))
7882
})
7983
}
8084

middleware/router_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ func TestRouterMiddleware(t *testing.T) {
4040
require.NoError(t, err)
4141

4242
mw.ServeHTTP(recorder, request)
43+
assert.Equal(t, "application/json", recorder.Header().Get("Content-Type"))
4344
assert.Equal(t, http.StatusMethodNotAllowed, recorder.Code)
4445

4546
methods := strings.Split(recorder.Header().Get("Allow"), ",")
@@ -51,6 +52,7 @@ func TestRouterMiddleware(t *testing.T) {
5152
require.NoError(t, err)
5253

5354
mw.ServeHTTP(recorder, request)
55+
assert.Equal(t, "application/json", recorder.Header().Get("Content-Type"))
5456
assert.Equal(t, http.StatusNotFound, recorder.Code)
5557

5658
recorder = httptest.NewRecorder()

0 commit comments

Comments
 (0)