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: do not panic when encountering external schemas #729

Merged
merged 1 commit into from
Feb 16, 2025
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
39 changes: 39 additions & 0 deletions huma_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2144,6 +2144,45 @@ Content-Type: text/plain
assert.Equal(t, 256, resp.Code)
},
},
{
Name: "response-external-schema",
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",
Responses: map[string]*huma.Response{
"200": {
Description: "Success",
Content: map[string]*huma.MediaType{
"application/json": {
Schema: &huma.Schema{
// Using an external schema should not break.
// https://github.com/danielgtaylor/huma/issues/703
Ref: "http://example.com/schemas/foo.json",
},
},
},
},
},
}, func(ctx context.Context, input *struct{}) (*Resp, error) {
resp := &Resp{}
resp.Body.Greeting = "Hello, world!"
return resp, nil
})
},
Method: http.MethodGet,
URL: "/response",
Assert: func(t *testing.T, resp *httptest.ResponseRecorder) {
assert.Equal(t, http.StatusOK, resp.Code)
assert.JSONEq(t, `{"greeting":"Hello, world!"}`, resp.Body.String())
},
},
{
// Simulate a request with a body that came from another call, which
// includes the `$schema` field. It should be allowed to be passed
Expand Down
3 changes: 2 additions & 1 deletion transforms.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"path"
"reflect"
"strings"
)

type schemaField struct {
Expand Down Expand Up @@ -49,7 +50,7 @@ func NewSchemaLinkTransformer(prefix, schemasPath string) *SchemaLinkTransformer
}

func (t *SchemaLinkTransformer) addSchemaField(oapi *OpenAPI, content *MediaType) bool {
if content == nil || content.Schema == nil || content.Schema.Ref == "" {
if content == nil || content.Schema == nil || content.Schema.Ref == "" || !strings.HasPrefix(content.Schema.Ref, "#/") {
return true
}

Expand Down
Loading