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.
nnet/core/nnet_router.go

50 lines
942 B
Go

package core
import (
"errors"
"git.noahlan.cn/northlan/nnet/log"
"git.noahlan.cn/northlan/nnet/packet"
)
type nNetRouter struct {
handlers map[string]Handler
notFound Handler
}
func NewRouter() Router {
return &nNetRouter{
handlers: make(map[string]Handler),
}
}
func (r *nNetRouter) Handle(conn *Connection, p packet.IPacket) {
pkg, ok := p.(*packet.Packet)
if !ok {
log.Error(packet.ErrWrongMessage)
return
}
handler, ok := r.handlers[pkg.Header.Route]
if !ok {
if r.notFound == nil {
log.Error("message handler not found")
return
}
r.notFound.Handle(conn, p)
return
}
handler.Handle(conn, p)
}
func (r *nNetRouter) Register(matches interface{}, handler 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 Handler) {
r.notFound = handler
}