feat: 新增参数绑定接口

main
熊二 2 years ago
parent b41fdd7816
commit 460dc378ea
  1. 21
      app/net.go

@ -13,6 +13,11 @@ type Convertor[V any] func(s string) (V, error)
type HandlerFunc func(w *ResponseWriter, r *Request) type HandlerFunc func(w *ResponseWriter, r *Request)
type ParamGetter func(key string) (string, bool) type ParamGetter func(key string) (string, bool)
// Binder 参数绑定接口
type Binder interface {
Bind(r *Request) error
}
func GetParam[V any](r *Params, key string, def V, convertor Convertor[V], taps []TapFunc[V]) V { func GetParam[V any](r *Params, key string, def V, convertor Convertor[V], taps []TapFunc[V]) V {
var v V var v V
if str, ok := r.Get(key); ok { if str, ok := r.Get(key); ok {
@ -35,7 +40,7 @@ type Params struct {
} }
func NewParams(pg ParamGetter) *Params { func NewParams(pg ParamGetter) *Params {
return &Params{pg } return &Params{pg}
} }
func NewPathParams(r *Request) *Params { func NewPathParams(r *Request) *Params {
@ -101,7 +106,7 @@ func (u *Params) Uint(key string, def uint, taps ...TapFunc[uint]) uint {
func (u *Params) Uint32(key string, def uint32, taps ...TapFunc[uint32]) uint32 { func (u *Params) Uint32(key string, def uint32, taps ...TapFunc[uint32]) uint32 {
return GetParam[uint32](u, key, def, func(s string) (uint32, error) { return GetParam[uint32](u, key, def, func(s string) (uint32, error) {
n,e := strconv.ParseUint(s, 10, 64) n, e := strconv.ParseUint(s, 10, 64)
return uint32(n), e return uint32(n), e
}, taps) }, taps)
} }
@ -125,11 +130,10 @@ func (u *Params) Float64(key string, def float64, taps ...TapFunc[float64]) floa
}, taps) }, taps)
} }
type Request struct { type Request struct {
*http.Request *http.Request
*Params *Params
pathParams *Params pathParams *Params
queryParams *Params queryParams *Params
} }
@ -183,15 +187,15 @@ func (r *Request) QueryParams() *Params {
type ResponseWriter struct { type ResponseWriter struct {
http.ResponseWriter http.ResponseWriter
mutex sync.RWMutex mutex sync.RWMutex
sent bool sent bool
} }
func NewResponseWriter(w http.ResponseWriter) *ResponseWriter { func NewResponseWriter(w http.ResponseWriter) *ResponseWriter {
return &ResponseWriter{ return &ResponseWriter{
ResponseWriter: w, ResponseWriter: w,
mutex: sync.RWMutex{}, mutex: sync.RWMutex{},
sent: false, sent: false,
} }
} }
@ -265,4 +269,3 @@ func Handler(hf HandlerFunc) http.HandlerFunc {
hf(NewResponseWriter(w), NewRequest(r)) hf(NewResponseWriter(w), NewRequest(r))
} }
} }

Loading…
Cancel
Save