定制gin校验翻译

This commit is contained in:
guosl 2024-07-01 19:07:37 +08:00
parent 9f7d48f801
commit d67ba5fc1f
4 changed files with 18 additions and 10 deletions

2
.gitignore vendored
View File

@ -5,5 +5,5 @@ bin/
tmp/ tmp/
.metadata .metadata
.bak .bak
__.debug__* __debug*
*.yaml *.yaml

View File

@ -1,9 +1,9 @@
package validator package validator
import ( import (
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"strings"
"sync" "sync"
"github.com/gin-gonic/gin/binding" "github.com/gin-gonic/gin/binding"
@ -98,14 +98,14 @@ func (c *customValidator) registerValidation() error {
func (c *customValidator) translate(err error) error { func (c *customValidator) translate(err error) error {
if errs, ok := err.(validator.ValidationErrors); ok { if errs, ok := err.(validator.ValidationErrors); ok {
tErrMap := errs.Translate(c.translator) tErrMap := errs.Translate(c.translator)
if tErrMap != nil { errMsgs := make([]string, 0)
if errMsg, errTmp := json.Marshal(tErrMap); errTmp == nil {
return errors.New(string(errMsg)) for _, msg := range tErrMap {
} else { errMsgs = append(errMsgs, msg)
return fmt.Errorf("validator translate json marshal fail:%s", errTmp)
}
} }
return errors.New(strings.Join(errMsgs, ";"))
// todo 根据定制tag,输出定制的msg // todo 根据定制tag,输出定制的msg
// todo 翻译后的错误消息按另外的规则输出(当前json) // todo 翻译后的错误消息按另外的规则输出(当前json)
} }

View File

@ -8,11 +8,13 @@ import (
"busniess-user-center/pkg/middleware/decoder" "busniess-user-center/pkg/middleware/decoder"
"busniess-user-center/pkg/middleware/logger" "busniess-user-center/pkg/middleware/logger"
"busniess-user-center/pkg/middleware/recovery" "busniess-user-center/pkg/middleware/recovery"
"busniess-user-center/pkg/validator"
"busniess-user-center/server/user" "busniess-user-center/server/user"
"github.com/gin-contrib/gzip" "github.com/gin-contrib/gzip"
"github.com/gin-contrib/pprof" "github.com/gin-contrib/pprof"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/samber/do" "github.com/samber/do"
"go.uber.org/zap" "go.uber.org/zap"
@ -43,7 +45,9 @@ func RunWebServer(ctx context.Context) error {
} }
func newGinEngine() (*gin.Engine, error) { func newGinEngine() (*gin.Engine, error) {
setBindValidator()
engine := gin.New() engine := gin.New()
pprof.Register(engine) pprof.Register(engine)
// 设置解压插件 // 设置解压插件
@ -78,3 +82,7 @@ func registerWebRoute(engine *gin.Engine) error {
user.RegisterRoute(userApi) user.RegisterRoute(userApi)
return nil return nil
} }
func setBindValidator() {
binding.Validator = validator.NewValidator()
}

View File

@ -1,6 +1,6 @@
package proto package proto
type AddRequst struct { type AddRequst struct {
Name string Name string `binding:"required"`
Account string Account string `binding:"required"`
} }