From 8743f4073905b1959e1cdfcb783b3004a7a04642 Mon Sep 17 00:00:00 2001 From: black1552 Date: Tue, 3 Feb 2026 17:21:58 +0800 Subject: [PATCH] =?UTF-8?q?refactor(valid):=20=E4=BD=BF=E7=94=A8Gin?= =?UTF-8?q?=E5=86=85=E7=BD=AE=E9=AA=8C=E8=AF=81=E5=99=A8=E6=9B=BF=E4=BB=A3?= =?UTF-8?q?=E6=89=8B=E5=8A=A8=E5=88=9B=E5=BB=BA=E5=AE=9E=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 移除ApiResponse结构体并改用Gin绑定的validator实例,确保验证器与翻译器的一致性 --- .idea/GOHCache.xml | 581 +++++++++++++++++++++++++++++++++++++++++++++ valid/valid.go | 14 +- 2 files changed, 587 insertions(+), 8 deletions(-) create mode 100644 .idea/GOHCache.xml diff --git a/.idea/GOHCache.xml b/.idea/GOHCache.xml new file mode 100644 index 0000000..5f5b4de --- /dev/null +++ b/.idea/GOHCache.xml @@ -0,0 +1,581 @@ + + + + + + + + \ No newline at end of file diff --git a/valid/valid.go b/valid/valid.go index c2bcd68..ffbacfc 100644 --- a/valid/valid.go +++ b/valid/valid.go @@ -5,6 +5,7 @@ import ( "reflect" "strings" + "github.com/gin-gonic/gin/binding" "github.com/go-playground/locales/zh" ut "github.com/go-playground/universal-translator" "github.com/go-playground/validator/v10" @@ -18,13 +19,6 @@ var ( found bool ) -// -------------------------- 统一响应格式 -------------------------- -type ApiResponse struct { - Code int `json:"code"` - Msg string `json:"msg"` - Data interface{} `json:"data"` -} - // -------------------------- 初始化全局验证器+中文翻译器(关键:与Gin关联) -------------------------- func init() { // 1. 初始化中文本地化 @@ -40,7 +34,11 @@ func init() { // 3. 关键:获取 Gin 内置的 validator 实例(而非手动创建 new(validator.Validate)) // 保证 Gin 绑定参数时使用的是我们注册了翻译的这个验证器 - validate = validator.New() + if v, ok := binding.Validator.Engine().(*validator.Validate); ok { + validate = v + } else { + panic("获取 Gin 内置验证器失败") + } // 4. 注册中文翻译(核心:将验证器与中文翻译器绑定) err = zh_translations.RegisterDefaultTranslations(validate, trans)