package nnet import ( "errors" "fmt" "git.noahlan.cn/noahlan/nnet/conn" "git.noahlan.cn/noahlan/nnet/packet" rt "git.noahlan.cn/noahlan/nnet/router" "git.noahlan.cn/noahlan/ntool/nlog" ) type ( RouteMap struct { // 路由 Routes map[string]uint16 `json:"routes"` // route map to code Codes map[uint16]string `json:"codes"` // code map to route } Match struct { Route string // 路由 Code uint16 // 路由编码 } nRouter struct { routeMap *RouteMap handlers map[string]rt.Handler notFound rt.Handler } ) func NewRouteMap() *RouteMap { return &RouteMap{ Routes: make(map[string]uint16), Codes: make(map[uint16]string), } } func NewRouter() rt.Router { return &nRouter{ routeMap: NewRouteMap(), handlers: make(map[string]rt.Handler), } } func (r *nRouter) Handle(conn *conn.Connection, p packet.IPacket) { pkg, ok := p.(*Packet) if !ok { nlog.Error(packet.ErrWrongPacketType) return } handler, ok := r.handlers[pkg.Header.Route] if !ok { if r.notFound == nil { nlog.Error("message handler not found") return } r.notFound.Handle(conn, p) return } handler.Handle(conn, p) } func (r *nRouter) Register(matches any, handler rt.Handler) error { match, ok := matches.(Match) if !ok { return errors.New(fmt.Sprintf("the type of matches must be %T", Match{})) } r.handlers[match.Route] = handler // routeMap r.routeMap.Routes[match.Route] = match.Code r.routeMap.Codes[match.Code] = match.Route return nil } func (r *nRouter) SetNotFoundHandler(handler rt.Handler) { r.notFound = handler }