-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_callback.go
More file actions
68 lines (54 loc) · 1.61 KB
/
validate_callback.go
File metadata and controls
68 lines (54 loc) · 1.61 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
/*
* Copyright (c) 2024-2026 Mikhail Knyazhev <markus621@yandex.com>. All rights reserved.
* Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file.
*/
package validate
import (
"context"
"fmt"
"go.osspkg.com/validate/internal/pool"
"go.osspkg.com/validate/internal/util"
)
type Callback interface {
Optional(name Name, value any, opts ...any)
Require(name Name, value any, opts ...any)
}
var poolCallbackValidator = pool.New[*callbackValidator](func() *callbackValidator {
return &callbackValidator{params: make([]cvParam, 0, 32)}
})
type cvParam struct {
require bool
name Name
value any
opts []any
}
type callbackValidator struct {
params []cvParam
}
func (v *callbackValidator) Reset() {
v.params = v.params[:0]
}
func (v *callbackValidator) Optional(name Name, value any, opts ...any) {
v.params = append(v.params, cvParam{require: false, name: name, value: value, opts: opts})
}
func (v *callbackValidator) Require(name Name, value any, opts ...any) {
v.params = append(v.params, cvParam{require: true, name: name, value: value, opts: opts})
}
func (v *callbackValidator) handler(ctx context.Context, r resolver, p cvParam) error {
rule, ok := r.Resolve(p.name)
if !ok {
return fmt.Errorf("validator `%s` not found", p.name)
}
if !p.require && util.IsDefaultValue(p.value) {
return nil
}
return rule.Handle.ValidateHandle(ctx, p.value, p.opts...)
}
func (v *callbackValidator) run(ctx context.Context, r resolver) error {
for i := range v.params {
if err := v.handler(ctx, r, v.params[i]); err != nil {
return err
}
}
return nil
}