-
Notifications
You must be signed in to change notification settings - Fork 7
/
formatError.go
65 lines (52 loc) · 1.56 KB
/
formatError.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
package gpc
import (
"reflect"
"regexp"
"strings"
"sync"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
)
type FormatError struct {
Errors []FormatErrorMetadata `json:"errors"`
}
type FormatErrorMetadata struct {
Msg string `json:"msg"`
Param string `json:"param"`
Tag string `json:"tag"`
}
func formatError(err error, trans ut.Translator, customMessage interface{}) (*FormatError, error) {
var (
mutex *sync.RWMutex = new(sync.RWMutex)
errResponsePool *sync.Pool = new(sync.Pool)
)
errResponsePool.New = func() interface{} {
return new(FormatError)
}
errResponse := errResponsePool.Get().(*FormatError)
for i, e := range err.(validator.ValidationErrors) {
errResult := new(FormatErrorMetadata)
errResult.Param = e.StructField()
if _, ok := reflect.TypeOf(customMessage).Field(i).Tag.Lookup("gpc"); !ok {
errResult.Msg = e.Translate(trans)
} else {
strucField, _ := reflect.TypeOf(customMessage).FieldByName(e.StructField())
structTags := strucField.Tag.Get("gpc")
regexTag := regexp.MustCompile(`=+[\w].*`)
regexVal := regexp.MustCompile(`[\w]+=`)
tags := strings.Split(structTags, ",")
for j, v := range tags {
replacedTag := regexTag.ReplaceAllString(tags[j], "")
if replacedTag == e.ActualTag() {
errResult.Msg = regexVal.ReplaceAllString(v, "")
}
}
}
mutex.RLock()
defer mutex.RUnlock()
errResult.Tag = e.ActualTag()
errResponse.Errors = append(errResponse.Errors, *errResult)
}
errResponsePool.Put(errResponse)
return errResponse, nil
}