-
Notifications
You must be signed in to change notification settings - Fork 0
/
i18n.go
54 lines (43 loc) · 1.47 KB
/
i18n.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
package xiren
import (
"strings"
"github.com/go-playground/validator/v10"
"github.com/goexl/gox"
"github.com/goexl/gox/field"
"github.com/goexl/exception"
)
var _ = Localization
// Localization 取得本地化错误信息
func Localization(lang string, errs validator.ValidationErrors) (err error) {
translations := getTranslations(lang, errs)
// 得到的国际化字符串是一个带请求体的键值,类似于LoginReq.Password:错误消息
// 而我们需要的是password: 错误消息
fields := make([]gox.Field[any], 0, len(translations))
for _field, msg := range translations {
key := gox.String(_field[strings.IndexRune(_field, dot)+1:]).Switch().Camel().Upper().All().Build().Build()
fields = append(fields, field.New(key.Case(), msg))
}
err = exception.New().Message(exceptionValidate).Field(fields...).Build()
return
}
func getTranslations(lang string, errs validator.ValidationErrors) (translations validator.ValidationErrorsTranslations) {
splits := strings.Split(lang, separator)
for index := 0; index < len(splits); index++ {
if translate, found := translator.FindTranslator(lang); found {
translations = errs.Translate(translate)
} else if last := strings.LastIndex(lang, separator); -1 != last {
lang = lang[:last]
}
if nil != translations {
break
}
}
if nil != translations {
return
}
// 默认使用中文
if translate, found := translator.GetTranslator(langZh); found {
translations = errs.Translate(translate)
}
return
}