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.
52 lines
1.0 KiB
Go
52 lines
1.0 KiB
Go
package protocol
|
|
|
|
import (
|
|
"errors"
|
|
"git.noahlan.cn/noahlan/nnet/core"
|
|
"git.noahlan.cn/noahlan/nnet/entity"
|
|
"git.noahlan.cn/noahlan/nnet/packet"
|
|
"git.noahlan.cn/noahlan/ntools-go/core/nlog"
|
|
)
|
|
|
|
type nNetRouter struct {
|
|
handlers map[string]core.Handler
|
|
notFound core.Handler
|
|
}
|
|
|
|
func NewNNetRouter() core.Router {
|
|
return &nNetRouter{
|
|
handlers: make(map[string]core.Handler),
|
|
}
|
|
}
|
|
|
|
func (r *nNetRouter) Handle(entity entity.NetworkEntity, p packet.IPacket) {
|
|
pkg, ok := p.(*NNetPacket)
|
|
if !ok {
|
|
nlog.Error(ErrWrongMessage)
|
|
return
|
|
}
|
|
handler, ok := r.handlers[pkg.Header.Route]
|
|
if !ok {
|
|
if r.notFound == nil {
|
|
nlog.Error("message handler not found")
|
|
return
|
|
}
|
|
r.notFound.Handle(entity, p)
|
|
return
|
|
}
|
|
handler.Handle(entity, p)
|
|
}
|
|
|
|
func (r *nNetRouter) Register(matches interface{}, handler core.Handler) error {
|
|
route, ok := matches.(string)
|
|
if !ok {
|
|
return errors.New("the type of matches must be string")
|
|
}
|
|
r.handlers[route] = handler
|
|
return nil
|
|
}
|
|
|
|
func (r *nNetRouter) SetNotFoundHandler(handler core.Handler) {
|
|
r.notFound = handler
|
|
}
|