You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
1.6 KiB
Go
83 lines
1.6 KiB
Go
package core
|
|
|
|
import (
|
|
"git.noahlan.cn/noahlan/nnet/entity"
|
|
"git.noahlan.cn/noahlan/nnet/packet"
|
|
)
|
|
|
|
type (
|
|
Route struct {
|
|
Matches interface{} // 用于匹配的关键字段
|
|
Handler HandlerFunc // 处理方法
|
|
}
|
|
|
|
Router interface {
|
|
Handler
|
|
Register(matches interface{}, handler Handler) error
|
|
SetNotFoundHandler(handler Handler)
|
|
}
|
|
|
|
Constructor func(Handler) Handler
|
|
)
|
|
|
|
type Chain struct {
|
|
constructors []Constructor
|
|
}
|
|
|
|
func newChain(constructors ...Constructor) Chain {
|
|
return Chain{append(([]Constructor)(nil), constructors...)}
|
|
}
|
|
|
|
func (c Chain) Then(h Handler) Handler {
|
|
// TODO nil
|
|
|
|
for i := range c.constructors {
|
|
h = c.constructors[len(c.constructors)-1-i](h)
|
|
}
|
|
return h
|
|
}
|
|
|
|
func (c Chain) ThenFunc(fn HandlerFunc) Handler {
|
|
if fn == nil {
|
|
return c.Then(nil)
|
|
}
|
|
return c.Then(fn)
|
|
}
|
|
|
|
func (c Chain) Append(constructors ...Constructor) Chain {
|
|
newCons := make([]Constructor, 0, len(c.constructors)+len(constructors))
|
|
newCons = append(newCons, c.constructors...)
|
|
newCons = append(newCons, constructors...)
|
|
|
|
return Chain{newCons}
|
|
}
|
|
|
|
func (c Chain) Extend(chain Chain) Chain {
|
|
return c.Append(chain.constructors...)
|
|
}
|
|
|
|
type plainRouter struct {
|
|
handler Handler
|
|
notFound Handler
|
|
}
|
|
|
|
func NewDefaultRouter() Router {
|
|
return &plainRouter{}
|
|
}
|
|
|
|
func (p *plainRouter) Handle(entity entity.NetworkEntity, pkg packet.IPacket) {
|
|
if p.handler == nil {
|
|
return
|
|
}
|
|
p.handler.Handle(entity, pkg)
|
|
}
|
|
|
|
func (p *plainRouter) Register(_ interface{}, handler Handler) error {
|
|
p.handler = handler
|
|
return nil
|
|
}
|
|
|
|
func (p *plainRouter) SetNotFoundHandler(handler Handler) {
|
|
p.notFound = handler
|
|
}
|