chore: moved packages to v1
This commit is contained in:
1 parent
522ba1b639
commit
43e3a8a397
15 files changed
+26
-14
No files matched your search
@@ -0,0 +1,70 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
mcontext "github.com/abelith/gomax/v1/context"
|
||||
)
|
||||
|
||||
type Middleware func(next HandlerFunc) HandlerFunc
|
||||
|
||||
type route struct {
|
||||
h UpdateHandler
|
||||
filters []func(c *mcontext.Context) bool
|
||||
}
|
||||
|
||||
type Router struct {
|
||||
routes []route
|
||||
mw []Middleware
|
||||
}
|
||||
|
||||
func (r *Router) HandleUpdate(c *mcontext.Context) error {
|
||||
var current HandlerFunc = r.dispatch
|
||||
|
||||
for i := len(r.mw) - 1; i >= 0; i-- {
|
||||
current = r.mw[i](current)
|
||||
}
|
||||
|
||||
return current.HandleUpdate(c)
|
||||
}
|
||||
|
||||
func (r *Router) Use(mws ...Middleware) {
|
||||
r.mw = append(r.mw, mws...)
|
||||
}
|
||||
|
||||
func (r *Router) HandleFunc(h HandlerFunc, filters ...func(c *mcontext.Context) bool) {
|
||||
r.routes = append(r.routes, route{
|
||||
h: h,
|
||||
filters: filters,
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Router) Handle(h UpdateHandler, filters ...func(c *mcontext.Context) bool) {
|
||||
r.routes = append(r.routes, route{
|
||||
h: h,
|
||||
filters: filters,
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Router) dispatch(c *mcontext.Context) error {
|
||||
for _, rt := range r.routes {
|
||||
if match(rt.filters, c) {
|
||||
err := rt.h.HandleUpdate(c)
|
||||
if errors.Is(err, ErrRouteNotFound) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return ErrRouteNotFound
|
||||
}
|
||||
|
||||
func match(filters []func(c *mcontext.Context) bool, c *mcontext.Context) bool {
|
||||
for _, filter := range filters {
|
||||
if !filter(c) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
Reference in new issue
Block a user