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

fix: catch reflect.StructOf panics in schema transformer #375

Merged
merged 2 commits into from
Apr 12, 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
4 changes: 3 additions & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,6 @@ jobs:
with:
version: v1.57.2
- run: go test -coverprofile=coverage.txt -covermode=atomic ./...
- uses: codecov/codecov-action@v1
- uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }}
17 changes: 17 additions & 0 deletions huma_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1465,6 +1465,23 @@ func TestConvenienceMethods(t *testing.T) {
assert.Equal(t, "delete-things-by-thing-id", api.OpenAPI().Paths[path].Delete.OperationID)
}

type EmbeddedWithMethod struct{}

func (e EmbeddedWithMethod) Method() {}

func TestUnsupportedEmbeddedTypeWithMethods(t *testing.T) {
_, api := humatest.New(t, huma.DefaultConfig("Test API", "1.0.0"))

// Should not panic!
huma.Post(api, "/things", func(ctx context.Context, input *struct{}) (*struct {
Body struct {
EmbeddedWithMethod
}
}, error) {
return nil, nil
})
}

// func BenchmarkSecondDecode(b *testing.B) {
// //nolint: musttag
// type MediumSized struct {
Expand Down
25 changes: 18 additions & 7 deletions transforms.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package huma

import (
"bytes"
"fmt"
"path"
"reflect"
)
Expand Down Expand Up @@ -125,13 +126,23 @@ func (t *SchemaLinkTransformer) OnAddOperation(oapi *OpenAPI, op *Operation) {
}
}

newType := reflect.StructOf(fields)
info := t.types[typ]
info.t = newType
info.fields = fieldIndexes
info.ref = extra.Schema
info.header = "<" + extra.Schema + ">; rel=\"describedBy\""
t.types[typ] = info
func() {
defer func() {
if r := recover(); r != nil {
// Catch some scenarios that just aren't supported in Go at the
// moment. Logs an error so people know what's going on.
// https://github.com/danielgtaylor/huma/issues/371
fmt.Println("Warning: unable to create schema link for type", typ, ":", r)
}
}()
newType := reflect.StructOf(fields)
info := t.types[typ]
info.t = newType
info.fields = fieldIndexes
info.ref = extra.Schema
info.header = "<" + extra.Schema + ">; rel=\"describedBy\""
t.types[typ] = info
}()
}
}
}
Expand Down
Loading