go项目脚手架
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
sorbet/internal/util/echo_bind.go

43 lines
891 B

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
}