From 7f74b7d5f7b36cbdc15b6cb2c77c6585ed6af73c Mon Sep 17 00:00:00 2001 From: "Daniel G. Taylor" Date: Sat, 27 Apr 2024 19:38:27 -0700 Subject: [PATCH] fix: more robust nil check for link transformer --- huma_test.go | 24 ++++++++++++++++++++++++ transforms.go | 5 +++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/huma_test.go b/huma_test.go index 5aa6364b..9af8c405 100644 --- a/huma_test.go +++ b/huma_test.go @@ -1114,6 +1114,30 @@ Content of example2.txt. assert.Equal(t, `hello`, resp.Body.String()) }, }, + { + Name: "response-transform-nil-body", + Transformers: []huma.Transformer{ + huma.NewSchemaLinkTransformer("/", "/").Transform, + }, + Register: func(t *testing.T, api huma.API) { + huma.Get(api, "/transform", func(ctx context.Context, i *struct{}) (*struct { + Body *struct { + Field string `json:"field"` + } + }, error) { + return &struct { + Body *struct { + Field string `json:"field"` + } + }{}, nil + }) + }, + Method: http.MethodGet, + URL: "/transform", + Assert: func(t *testing.T, resp *httptest.ResponseRecorder) { + assert.Equal(t, http.StatusOK, resp.Code) + }, + }, { Name: "response-transform-error", Transformers: []huma.Transformer{ diff --git a/transforms.go b/transforms.go index c8600c03..9c5a0db2 100644 --- a/transforms.go +++ b/transforms.go @@ -150,7 +150,8 @@ func (t *SchemaLinkTransformer) OnAddOperation(oapi *OpenAPI, op *Operation) { // Transform is called for every response to add the `$schema` field and/or // the Link header pointing to the JSON Schema. func (t *SchemaLinkTransformer) Transform(ctx Context, status string, v any) (any, error) { - if v == nil { + vv := reflect.ValueOf(v) + if vv.Kind() == reflect.Pointer && vv.IsNil() { return v, nil } @@ -184,7 +185,7 @@ func (t *SchemaLinkTransformer) Transform(ctx Context, status string, v any) (an bufPool.Put(buf) // Copy over all the exported fields. - vv := reflect.Indirect(reflect.ValueOf(v)) + vv = reflect.Indirect(vv) for i, j := range info.fields { // Field 0 is the $schema field, so we need to offset the index by one. // There might have been unexported fields in the struct declared in the schema,