Skip to content

Commit

Permalink
Merge pull request #43 from danielgtaylor/default-status
Browse files Browse the repository at this point in the history
fix: accept status code 0 as default response
  • Loading branch information
danielgtaylor authored Apr 22, 2022
2 parents 02414da + f7e9477 commit 49db25b
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
4 changes: 2 additions & 2 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ func (c *hcontext) WriteHeader(status int) {
if c.op != nil {
allowed := []string{}
for _, r := range c.op.responses {
if r.status == status {
if r.status == status || r.status == 0 {
for _, h := range r.headers {
allowed = append(allowed, h)
}
Expand Down Expand Up @@ -273,7 +273,7 @@ func (c *hcontext) writeModel(ct string, status int, model interface{}) {
statuses := []string{}
for _, r := range c.op.responses {
statuses = append(statuses, fmt.Sprintf("%d", r.status))
if r.status == status {
if r.status == status || r.status == 0 {
responses = append(responses, r)
if r.model != nil {
names = append(names, r.model.Name())
Expand Down
3 changes: 3 additions & 0 deletions operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ func (o *Operation) toOpenAPI(components *oaComponents) *gabs.Container {
// responses
for i, resp := range o.responses {
status := fmt.Sprintf("%v", resp.status)
if resp.status == 0 {
status = "default"
}
doc.Set(resp.description, "responses", status, "description")

headers := resp.headers
Expand Down
16 changes: 16 additions & 0 deletions router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -462,3 +462,19 @@ func TestSubResource(t *testing.T) {
// Do nothing
})
}

func TestDefaultResponse(t *testing.T) {
app := newTestRouter()

// This should not crash.
app.Resource("/").Get("get-root", "docs", NewResponse(0, "Default repsonse")).Run(func(ctx Context) {
ctx.WriteHeader(http.StatusOK)
})

w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/", nil)
app.ServeHTTP(w, req)

// This should not panic and should return the 200 OK
assert.Equal(t, http.StatusOK, w.Result().StatusCode)
}

0 comments on commit 49db25b

Please sign in to comment.