package util import ( "github.com/labstack/echo/v4" "sorbet/pkg/rsp" ) // RequestGuarder 参数守卫函数签名 type RequestGuarder[T any] func(c echo.Context, req *T) error // Bind 将提交的参数绑定到泛型 T 的实例上 func Bind[T any](c echo.Context, guards ...RequestGuarder[T]) (*T, error) { var req T if err := c.Bind(&req); err != nil { return nil, err } if err := c.Validate(&req); err != nil { return nil, err } for _, guard := range guards { if err := guard(c, &req); err != nil { return nil, err } } return &req, nil } func BindId(c echo.Context, must bool) (uint, error) { request, err := Bind[struct { ID uint `json:"id" xml:"id" path:"id"` }](c) if err != nil { return 0, err } if must { if request.ID <= 0 { return 0, rsp.ErrBadParams } } else if request.ID < 0 { return 0, rsp.ErrBadParams } return request.ID, err }