Skip to content

Commit

Permalink
Merge pull request #546 from danielgtaylor/handle-response-nil
Browse files Browse the repository at this point in the history
fix: if err & response are nil, return default status
  • Loading branch information
danielgtaylor authored Aug 17, 2024
2 parents 912f02e + fc4ed20 commit 37667b6
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 37667b6

Please sign in to comment.