Skip to content

Commit

Permalink
fix: prevent panic on examples for pointer field types
Browse files Browse the repository at this point in the history
  • Loading branch information
danielgtaylor committed Oct 22, 2023
1 parent fb69658 commit 606e9d7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
14 changes: 11 additions & 3 deletions schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ func floatTag(f reflect.StructField, tag string) *float64 {

func jsonTagValue(f reflect.StructField, t reflect.Type, value string) any {
// Special case: strings don't need quotes.
if t.Kind() == reflect.String {
if t.Kind() == reflect.String || (t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.String) {
return value
}

Expand Down Expand Up @@ -262,11 +262,19 @@ func jsonTagValue(f reflect.StructField, t reflect.Type, value string) any {
tmp = reflect.Append(tmp, vv.Index(i).Elem().Convert(t.Elem()))
}
v = tmp.Interface()
} else if !tv.ConvertibleTo(t) {
} else if !tv.ConvertibleTo(deref(t)) {
panic(fmt.Errorf("unable to convert %v to %v: %w", tv, t, ErrSchemaInvalid))
}

v = reflect.ValueOf(v).Convert(t).Interface()
converted := reflect.ValueOf(v).Convert(deref(t))
if t.Kind() == reflect.Ptr {
// Special case: if the field is a pointer, we need to get a pointer
// to the converted value.
tmp := reflect.New(t.Elem())
tmp.Elem().Set(converted)
converted = tmp
}
v = converted.Interface()
}

return v
Expand Down
23 changes: 23 additions & 0 deletions schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,29 @@ func TestSchema(t *testing.T) {
}
}`,
},
{
name: "fiel-pointer-example",
input: struct {
Int *int64 `json:"int" example:"123"`
Str *string `json:"str" example:"foo"`
}{},
expected: `{
"type": "object",
"additionalProperties": false,
"required": ["int", "str"],
"properties": {
"int": {
"type": "integer",
"format": "int64",
"examples": [123]
},
"str": {
"type": "string",
"examples": ["foo"]
}
}
}`,
},
{
name: "panic-bool",
input: struct {
Expand Down

0 comments on commit 606e9d7

Please sign in to comment.