-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathschema.go
More file actions
108 lines (97 loc) · 2.37 KB
/
schema.go
File metadata and controls
108 lines (97 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package check
import (
"fmt"
"strings"
)
// Schema is the core interface all schemas implement.
type Schema interface {
// Parse validates and returns the (possibly transformed) value, or an error.
Parse(value any) (any, error)
// Validate returns all validation errors (not just the first).
Validate(value any) []ValidationError
// IsOptional reports whether this schema accepts nil values.
IsOptional() bool
}
// ValidationError represents a single validation failure.
type ValidationError struct {
Path string // dot-separated path, e.g. "address.city"
Message string // human-readable message
Value any // the offending value
}
func (e ValidationError) Error() string {
if e.Path != "" {
return fmt.Sprintf("%s: %s", e.Path, e.Message)
}
return e.Message
}
// ValidationErrors is a collection of validation errors that implements error.
type ValidationErrors []ValidationError
func (ve ValidationErrors) Error() string {
if len(ve) == 0 {
return ""
}
var b strings.Builder
b.WriteString("Validation failed:\n")
for _, e := range ve {
b.WriteString(" • ")
b.WriteString(e.Error())
b.WriteString("\n")
}
return b.String()
}
// prefixErrors adds a path prefix to all errors.
func prefixErrors(prefix string, errs []ValidationError) []ValidationError {
out := make([]ValidationError, len(errs))
for i, e := range errs {
if e.Path != "" {
out[i] = ValidationError{Path: prefix + "." + e.Path, Message: e.Message, Value: e.Value}
} else {
out[i] = ValidationError{Path: prefix, Message: e.Message, Value: e.Value}
}
}
return out
}
// toFloat64 converts numeric types to float64.
func toFloat64(v any) (float64, bool) {
switch n := v.(type) {
case int:
return float64(n), true
case int8:
return float64(n), true
case int16:
return float64(n), true
case int32:
return float64(n), true
case int64:
return float64(n), true
case float32:
return float64(n), true
case float64:
return n, true
}
return 0, false
}
// toInt converts numeric types to int.
func toInt(v any) (int, bool) {
switch n := v.(type) {
case int:
return n, true
case int8:
return int(n), true
case int16:
return int(n), true
case int32:
return int(n), true
case int64:
return int(n), true
case float64:
if n == float64(int(n)) {
return int(n), true
}
case float32:
if n == float32(int(n)) {
return int(n), true
}
}
return 0, false
}