ensureType panics if the given value does not match the JSON Schema type.
(r Registry, fieldName string, s *Schema, value string, v any)
| 392 | |
| 393 | // ensureType panics if the given value does not match the JSON Schema type. |
| 394 | func ensureType(r Registry, fieldName string, s *Schema, value string, v any) { |
| 395 | if s.Ref != "" { |
| 396 | s = r.SchemaFromRef(s.Ref) |
| 397 | if s == nil { |
| 398 | // We may not have access to this type, e.g., custom schema provided |
| 399 | // by the user with remote refs. Skip validation. |
| 400 | return |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | switch s.Type { |
| 405 | case TypeBoolean: |
| 406 | if _, ok := v.(bool); !ok { |
| 407 | panic(fmt.Errorf("invalid boolean tag value '%s' for field '%s': %w", value, fieldName, ErrSchemaInvalid)) |
| 408 | } |
| 409 | case TypeInteger, TypeNumber: |
| 410 | if _, ok := v.(float64); !ok { |
| 411 | panic(fmt.Errorf("invalid number tag value '%s' for field '%s': %w", value, fieldName, ErrSchemaInvalid)) |
| 412 | } |
| 413 | |
| 414 | if s.Type == TypeInteger { |
| 415 | if v.(float64) != float64(int(v.(float64))) { |
| 416 | panic(fmt.Errorf("invalid integer tag value '%s' for field '%s': %w", value, fieldName, ErrSchemaInvalid)) |
| 417 | } |
| 418 | } |
| 419 | case TypeString: |
| 420 | if _, ok := v.(string); !ok { |
| 421 | panic(fmt.Errorf("invalid string tag value '%s' for field '%s': %w", value, fieldName, ErrSchemaInvalid)) |
| 422 | } |
| 423 | case TypeArray: |
| 424 | if _, ok := v.([]any); !ok { |
| 425 | panic(fmt.Errorf("invalid array tag value '%s' for field '%s': %w", value, fieldName, ErrSchemaInvalid)) |
| 426 | } |
| 427 | |
| 428 | if s.Items != nil { |
| 429 | for i, item := range v.([]any) { |
| 430 | b, _ := json.Marshal(item) |
| 431 | ensureType(r, fieldName+"["+strconv.Itoa(i)+"]", s.Items, string(b), item) |
| 432 | } |
| 433 | } |
| 434 | case TypeObject: |
| 435 | if _, ok := v.(map[string]any); !ok { |
| 436 | panic(fmt.Errorf("invalid object tag value '%s' for field '%s': %w", value, fieldName, ErrSchemaInvalid)) |
| 437 | } |
| 438 | |
| 439 | for name, prop := range s.Properties { |
| 440 | if val, ok := v.(map[string]any)[name]; ok { |
| 441 | b, _ := json.Marshal(val) |
| 442 | ensureType(r, fieldName+"."+name, prop, string(b), val) |
| 443 | } |
| 444 | } |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | // convertType panics if the given value does not match or cannot be converted |
| 449 | // to the field's Go type. |
no test coverage detected
searching dependent graphs…