diff --git a/reflect.go b/reflect.go index 85e4beb..b41e6c4 100644 --- a/reflect.go +++ b/reflect.go @@ -1113,57 +1113,36 @@ func (r *Reflector) walkProperties(v reflect.Value, parent *Schema, rc *ReflectC } func checkInlineValue(propertySchema *Schema, field reflect.StructField, tag string, setter func(interface{}) *Schema) error { - var val interface{} + var ( + val interface{} + t SimpleType + + i *int64 + f *float64 + s *string + b *bool + ) - var t SimpleType if propertySchema.Type != nil && propertySchema.Type.SimpleTypes != nil { t = *propertySchema.Type.SimpleTypes } - switch t { //nolint:exhaustive // Covered by default case. - case Integer: - var v *int64 - - if err := refl.ReadIntPtrTag(field.Tag, tag, &v); err != nil { - return fmt.Errorf("parsing %s for %s: %w", tag, t, err) - } - - if v != nil { - val = *v - } - case Number: - var v *float64 - - if err := refl.ReadFloatPtrTag(field.Tag, tag, &v); err != nil { - return fmt.Errorf("parsing %s for %s: %w", tag, t, err) - } - - if v != nil { - val = *v - } - - case String: - var v *string - - refl.ReadStringPtrTag(field.Tag, tag, &v) - - if v != nil { - val = *v - } - - case Boolean: - var v *bool + _ = refl.ReadIntPtrTag(field.Tag, tag, &i) //nolint:errcheck + _ = refl.ReadFloatPtrTag(field.Tag, tag, &f) //nolint:errcheck + _ = refl.ReadBoolPtrTag(field.Tag, tag, &b) //nolint:errcheck + refl.ReadStringPtrTag(field.Tag, tag, &s) - if err := refl.ReadBoolPtrTag(field.Tag, tag, &v); err != nil { - return fmt.Errorf("parsing %s for %s: %w", tag, t, err) - } - - if v != nil { - val = *v - } - case Null: + switch { + case propertySchema.HasType(Number) && f != nil: + val = *f + case propertySchema.HasType(Integer) && i != nil: + val = *i + case propertySchema.HasType(Boolean) && b != nil: + val = *b + case propertySchema.HasType(String) && s != nil: + val = *s + case t == Null: // No default for type null. - default: var v string diff --git a/reflect_test.go b/reflect_test.go index f6e8b9d..4ef589f 100644 --- a/reflect_test.go +++ b/reflect_test.go @@ -1918,3 +1918,34 @@ func TestReflector_AddOperation_rawSchema(t *testing.T) { "type":"object" }`, s) } + +type Discover string + +const ( + DiscoverAll Discover = "all" + DiscoverNone Discover = "none" +) + +func (d *Discover) Enum() []interface{} { + return []interface{}{DiscoverAll, DiscoverNone} +} + +func TestReflector_Reflect_ptrDefault(t *testing.T) { + type NewThing struct { + DiscoverMode *Discover `json:"discover,omitempty" default:"all"` + } + + r := jsonschema.Reflector{} + + s, err := r.Reflect(NewThing{}) + require.NoError(t, err) + assertjson.EqMarshal(t, `{ + "definitions":{ + "JsonschemaGoTestDiscover":{"enum":["all","none"],"type":["null","string"]} + }, + "properties":{ + "discover":{"$ref":"#/definitions/JsonschemaGoTestDiscover","default":"all"} + }, + "type":"object" + }`, s) +}