Skip to content

Commit

Permalink
fix: if err & response are nil, return default status
Browse files Browse the repository at this point in the history
  • Loading branch information
danielgtaylor committed Aug 17, 2024
1 parent 912f02e commit fc4ed20
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
7 changes: 7 additions & 0 deletions huma.go
Original file line number Diff line number Diff line change
Expand Up @@ -1379,6 +1379,13 @@ func Register[I, O any](api API, op Operation, handler func(context.Context, *I)
return
}

if output == nil {
// Special case: No err or output, so just set the status code and return.
// This is a weird case, but it's better than panicking or returning 500.
ctx.SetStatus(op.DefaultStatus)
return
}

// Serialize output headers
ct := ""
vo := reflect.ValueOf(output).Elem()
Expand Down
24 changes: 24 additions & 0 deletions huma_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1432,6 +1432,30 @@ Content of example2.txt.
assert.JSONEq(t, `{"$schema": "https:///schemas/RespBody.json", "greeting":"Hello, world!"}`, resp.Body.String())
},
},
{
Name: "response-nil",
Register: func(t *testing.T, api huma.API) {
type Resp struct {
Body struct {
Greeting string `json:"greeting"`
}
}

huma.Register(api, huma.Operation{
Method: http.MethodGet,
Path: "/response",
}, func(ctx context.Context, input *struct{}) (*Resp, error) {
return nil, nil
})
},
Method: http.MethodGet,
URL: "/response",
Assert: func(t *testing.T, resp *httptest.ResponseRecorder) {
// This should not panic and should return the default status code,
// which for responses which normally have a body is 200.
assert.Equal(t, http.StatusOK, resp.Code)
},
},
{
Name: "response-raw",
Register: func(t *testing.T, api huma.API) {
Expand Down

0 comments on commit fc4ed20

Please sign in to comment.