Skip to content

Commit

Permalink
Merge pull request #148 from danielgtaylor/pointer-examples
Browse files Browse the repository at this point in the history
fix: prevent panic on examples for pointer field types
  • Loading branch information
danielgtaylor authored Oct 22, 2023
2 parents fb69658 + 7902577 commit e25de1a
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 10 deletions.
26 changes: 17 additions & 9 deletions schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ func boolTag(f reflect.StructField, tag string) bool {
} else if v == "false" {
return false
} else {
panic("invalid bool tag '" + tag + "' for field '" + f.Name + "': " + v)
panic(fmt.Errorf("invalid bool tag '%s' for field '%s': %v", tag, f.Name, v))
}
}
return false
Expand All @@ -209,7 +209,7 @@ func intTag(f reflect.StructField, tag string) *int {
if i, err := strconv.Atoi(v); err == nil {
return &i
} else {
panic("invalid int tag '" + tag + "' for field '" + f.Name + "': " + v + " (" + err.Error() + ")")
panic(fmt.Errorf("invalid int tag '%s' for field '%s': %v (%w)", tag, f.Name, v, err))
}
}
return nil
Expand All @@ -220,15 +220,15 @@ func floatTag(f reflect.StructField, tag string) *float64 {
if i, err := strconv.ParseFloat(v, 64); err == nil {
return &i
} else {
panic("invalid float tag '" + tag + "' for field '" + f.Name + "': " + v + " (" + err.Error() + ")")
panic(fmt.Errorf("invalid float tag '%s' for field '%s': %v (%w)", tag, f.Name, v, err))
}
}
return nil
}

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 All @@ -243,7 +243,7 @@ func jsonTagValue(f reflect.StructField, t reflect.Type, value string) any {

var v any
if err := json.Unmarshal([]byte(value), &v); err != nil {
panic("invalid tag for field '" + f.Name + "': " + err.Error())
panic(fmt.Errorf("invalid tag for field '%s': %w", f.Name, err))
}

vv := reflect.ValueOf(v)
Expand All @@ -256,17 +256,25 @@ func jsonTagValue(f reflect.StructField, t reflect.Type, value string) any {
tmp := reflect.MakeSlice(t, 0, vv.Len())
for i := 0; i < vv.Len(); i++ {
if !vv.Index(i).Elem().Type().ConvertibleTo(t.Elem()) {
panic(fmt.Errorf("unable to convert %v to %v: %w", vv.Index(i).Interface(), t.Elem(), ErrSchemaInvalid))
panic(fmt.Errorf("unable to convert %v to %v for field '%s': %w", vv.Index(i).Interface(), t.Elem(), f.Name, ErrSchemaInvalid))
}

tmp = reflect.Append(tmp, vv.Index(i).Elem().Convert(t.Elem()))
}
v = tmp.Interface()
} else if !tv.ConvertibleTo(t) {
panic(fmt.Errorf("unable to convert %v to %v: %w", tv, t, ErrSchemaInvalid))
} else if !tv.ConvertibleTo(deref(t)) {
panic(fmt.Errorf("unable to convert %v to %v for field '%s': %w", tv, t, f.Name, 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
32 changes: 31 additions & 1 deletion 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: "field-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 Expand Up @@ -397,14 +420,21 @@ func TestSchema(t *testing.T) {
}{},
panics: `invalid tag for field 'Value': invalid character 'b' looking for beginning of value`,
},
{
name: "panic-json-type",
input: struct {
Value int `json:"value" example:"true"`
}{},
panics: `unable to convert bool to int for field 'Value': schema is invalid`,
},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := NewMapRegistry("#/components/schemas/", DefaultSchemaNamer)

if c.panics != "" {
assert.PanicsWithValue(t, c.panics, func() {
assert.PanicsWithError(t, c.panics, func() {
r.Schema(reflect.TypeOf(c.input), false, "")
})
} else {
Expand Down

0 comments on commit e25de1a

Please sign in to comment.