-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
84 lines (73 loc) · 1.73 KB
/
utils.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package gromer
import (
"fmt"
"reflect"
"strings"
"time"
"github.com/go-playground/validator/v10"
"github.com/imdario/mergo"
"github.com/segmentio/go-camelcase"
)
var Validator = validator.New()
var ValidatorErrorMap = map[string]string{
"required": "is required",
}
type timeTransformer struct {
}
func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
if typ == reflect.TypeOf(time.Time{}) {
return func(dst, src reflect.Value) error {
if dst.CanSet() {
srcResult := src.MethodByName("IsZero").Call([]reflect.Value{})
if !srcResult[0].Bool() {
dst.Set(src)
}
}
return nil
}
}
return nil
}
func Merge(dst interface{}, src interface{}) error {
err := mergo.Merge(dst, src, mergo.WithOverride, mergo.WithTransformers(timeTransformer{}))
if err != nil {
return err
}
return Validate(dst)
}
func Validate(dst interface{}) error {
return Validator.Struct(dst)
}
func RegisterValidation(k, msg string, validate func(fl validator.FieldLevel) bool) {
ValidatorErrorMap[k] = msg
Validator.RegisterValidation(k, validate)
}
func GetValidationError(err validator.ValidationErrors) map[string]string {
emap := map[string]string{}
for _, e := range err {
parts := strings.Split(e.StructNamespace(), ".")
lowerParts := []string{}
for _, p := range parts[1:] {
lowerParts = append(lowerParts, camelcase.Camelcase(p))
}
k := strings.Join(lowerParts, ".")
errorMsg, ok := ValidatorErrorMap[e.Tag()]
if ok {
emap[k] = errorMsg
} else {
emap[k] = "is not valid" // e.Error()
}
}
return emap
}
func Zero[T any](s ...T) T {
var zero T
return zero
}
func Default[S any](a, b S) S {
va := fmt.Sprintf("%v", a)
if va == "" || va == "0" {
return b
}
return a
}