From d67ba5fc1f2e900ccfbceaa0615ac2e6730f4deb Mon Sep 17 00:00:00 2001 From: guosl Date: Mon, 1 Jul 2024 19:07:37 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9A=E5=88=B6gin=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 +- pkg/validator/validator.go | 14 +++++++------- server/http.go | 8 ++++++++ server/user/proto/request.go | 4 ++-- 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/.gitignore b/.gitignore index af80660..e33ea12 100644 --- a/.gitignore +++ b/.gitignore @@ -5,5 +5,5 @@ bin/ tmp/ .metadata .bak -__.debug__* +__debug* *.yaml \ No newline at end of file diff --git a/pkg/validator/validator.go b/pkg/validator/validator.go index 41cde51..d1d1360 100644 --- a/pkg/validator/validator.go +++ b/pkg/validator/validator.go @@ -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) } diff --git a/server/http.go b/server/http.go index 7c18a07..167ac2f 100644 --- a/server/http.go +++ b/server/http.go @@ -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() +} diff --git a/server/user/proto/request.go b/server/user/proto/request.go index f432174..67f0036 100644 --- a/server/user/proto/request.go +++ b/server/user/proto/request.go @@ -1,6 +1,6 @@ package proto type AddRequst struct { - Name string - Account string + Name string `binding:"required"` + Account string `binding:"required"` }