-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgod.go
More file actions
88 lines (77 loc) · 1.77 KB
/
Copy pathgod.go
File metadata and controls
88 lines (77 loc) · 1.77 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
package god
import (
"fmt"
"strings"
)
type ValidationError struct {
Field string
Message string
Value interface{}
Code string
}
func (e ValidationError) Error() string {
if e.Field != "" {
return fmt.Sprintf("%s: %s", e.Field, e.Message)
}
return e.Message
}
type ValidationResult struct {
Valid bool
Errors []ValidationError
Value interface{}
}
func (r ValidationResult) Error() error {
if r.Valid {
return nil
}
var messages []string
for _, err := range r.Errors {
messages = append(messages, err.Error())
}
return fmt.Errorf("validation failed: %s", strings.Join(messages, "; "))
}
type Schema interface {
Validate(value interface{}) ValidationResult
Optional() Schema
Required() Schema
Default(value interface{}) Schema
}
type BaseSchema struct {
isOptional bool
isRequired bool
defaultValue interface{}
hasDefault bool
}
func (s *BaseSchema) setOptional() {
s.isOptional = true
s.isRequired = false
}
func (s *BaseSchema) setRequired() {
s.isRequired = true
s.isOptional = false
}
func (s *BaseSchema) setDefault(value interface{}) {
s.defaultValue = value
s.hasDefault = true
}
func (s *BaseSchema) handleNil(value interface{}) (interface{}, bool, ValidationResult) {
if value == nil {
if s.hasDefault {
return s.defaultValue, false, ValidationResult{Valid: true, Value: s.defaultValue}
}
if s.isOptional {
return nil, true, ValidationResult{Valid: true, Value: nil}
}
if s.isRequired {
return nil, true, ValidationResult{
Valid: false,
Errors: []ValidationError{{Message: "field is required", Code: "required"}},
}
}
return nil, true, ValidationResult{
Valid: false,
Errors: []ValidationError{{Message: "field is required", Code: "required"}},
}
}
return value, false, ValidationResult{}
}