/
validator.go
64 lines (51 loc) · 1.19 KB
/
validator.go
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
package api
import (
"bytes"
"encoding/json"
"fmt"
"github.com/labstack/gommon/log"
"github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4"
)
type validatorImpl struct {
validator *validator.Validate
}
func (v *validatorImpl) Validate(i interface{}) error {
if err := v.validator.Struct(i); err != nil {
return err
}
return nil
}
func NewValidator() echo.Validator {
return &validatorImpl{validator: validator.New()}
}
type binderImpl struct{}
func (b *binderImpl) Bind(i interface{}, ctx echo.Context) error {
db := new(echo.DefaultBinder)
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(ctx.Request().Body)
if err != nil {
log.Errorf("Unmarshal error: %s", err)
return err
}
err = json.Unmarshal(buf.Bytes(), i)
if err != nil {
log.Errorf("Unmarshal error: %s", err)
}
if err := db.BindQueryParams(ctx, i); err != nil {
return fmt.Errorf("%v", err)
}
if err := db.BindPathParams(ctx, i); err != nil {
return fmt.Errorf("%v", err)
}
if err := db.BindHeaders(ctx, i); err != nil {
return fmt.Errorf("%v", err)
}
if err := ctx.Validate(i); err != nil {
return fmt.Errorf("%v", err)
}
return nil
}
func NewBinder() echo.Binder {
return &binderImpl{}
}