From 0230955934c7b55ee6f12019e72b489a87168462 Mon Sep 17 00:00:00 2001 From: Oleksandr Redko Date: Thu, 3 Oct 2024 11:53:12 +0300 Subject: [PATCH] refactor: use type switch instead of if-else --- huma.go | 19 ++++++++++--------- schema.go | 7 ++++--- validate.go | 7 ++++--- validate_test.go | 5 +++-- 4 files changed, 21 insertions(+), 17 deletions(-) diff --git a/huma.go b/huma.go index 9ef44a72..e00b7ac7 100644 --- a/huma.go +++ b/huma.go @@ -1334,17 +1334,18 @@ func Register[I, O any](api API, op Operation, handler func(context.Context, *I) elem.Set(item) item = ptr } - if resolver, ok := item.Interface().(Resolver); ok { - if errs := resolver.Resolve(ctx); len(errs) > 0 { - res.Errors = append(res.Errors, errs...) - } - } else if resolver, ok := item.Interface().(ResolverWithPath); ok { - if errs := resolver.Resolve(ctx, pb); len(errs) > 0 { - res.Errors = append(res.Errors, errs...) - } - } else { + var errs []error + switch resolver := item.Interface().(type) { + case Resolver: + errs = resolver.Resolve(ctx) + case ResolverWithPath: + errs = resolver.Resolve(ctx, pb) + default: panic("matched resolver cannot be run, please file a bug") } + if len(errs) > 0 { + res.Errors = append(res.Errors, errs...) + } }) if len(res.Errors) > 0 { diff --git a/schema.go b/schema.go index b1e9b288..d330c29b 100644 --- a/schema.go +++ b/schema.go @@ -331,11 +331,12 @@ func (s *Schema) PrecomputeMessages() { func boolTag(f reflect.StructField, tag string, def bool) bool { if v := f.Tag.Get(tag); v != "" { - if v == "true" { + switch v { + case "true": return true - } else if v == "false" { + case "false": return false - } else { + default: panic(fmt.Errorf("invalid bool tag '%s' for field '%s': %v", tag, f.Name, v)) } } diff --git a/validate.go b/validate.go index ac9f1d8d..03487d9c 100644 --- a/validate.go +++ b/validate.go @@ -520,11 +520,12 @@ func Validate(r Registry, s *Schema, path *PathBuffer, mode ValidateMode, v any, return } case TypeObject: - if vv, ok := v.(map[string]any); ok { + switch vv := v.(type) { + case map[string]any: handleMapString(r, s, path, mode, vv, res) - } else if vv, ok := v.(map[any]any); ok { + case map[any]any: handleMapAny(r, s, path, mode, vv, res) - } else { + default: res.Add(path, v, validation.MsgExpectedObject) return } diff --git a/validate_test.go b/validate_test.go index deb617a4..1c358607 100644 --- a/validate_test.go +++ b/validate_test.go @@ -1476,10 +1476,11 @@ func BenchmarkValidate(b *testing.B) { input := test.input if s.Type == huma.TypeObject && s.Properties["value"] != nil { - if i, ok := input.(map[string]any); ok { + switch i := input.(type) { + case map[string]any: input = i["value"] s = s.Properties["value"] - } else if i, ok := input.(map[any]any); ok { + case map[any]any: input = i["value"] s = s.Properties["value"] }