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 }