Files
workspace/code/allapp/allapp-go-v3/internal/httpx/request.go
T
2026-04-17 17:25:15 +08:00

36 lines
606 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package httpx
import (
"reflect"
"github.com/go-playground/validator/v10"
"github.com/gofiber/fiber/v3"
)
var validate = validator.New()
func BindAndValidate(c fiber.Ctx, v any) error {
// 1️⃣ 绑定 JSON
if err := c.Bind().Body(v); err != nil {
return err
}
// 2️⃣ 只允许 struct 校验(先不支持 slice)
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
// 如果是 slice,直接跳过校验
if rv.Kind() == reflect.Slice {
return nil
}
// 3️⃣ struct 校验
if err := validate.Struct(v); err != nil {
return err
}
return nil
}