定制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/
.metadata
.bak
__.debug__*
__debug*
*.yaml

View File

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

View File

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

View File

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