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.
50 lines
960 B
Go
50 lines
960 B
Go
package core
|
|
|
|
import (
|
|
"errors"
|
|
"git.noahlan.cn/northlan/nnet/internal/log"
|
|
"git.noahlan.cn/northlan/nnet/internal/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
|
|
}
|