|
|
|
package protocol
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"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"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
Routes = make(map[string]uint16) // route map to code
|
|
|
|
Codes = make(map[uint16]string) // code map to route
|
|
|
|
)
|
|
|
|
|
|
|
|
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 // 路由编码
|
|
|
|
}
|
|
|
|
|
|
|
|
nNetRouter struct {
|
|
|
|
routeMap *RouteMap
|
|
|
|
handlers map[string]core.Handler
|
|
|
|
notFound core.Handler
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewRouteMap() *RouteMap {
|
|
|
|
return &RouteMap{
|
|
|
|
Routes: make(map[string]uint16),
|
|
|
|
Codes: make(map[uint16]string),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewNNetRouter() core.Router {
|
|
|
|
return &nNetRouter{
|
|
|
|
routeMap: NewRouteMap(),
|
|
|
|
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 {
|
|
|
|
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 *nNetRouter) SetNotFoundHandler(handler core.Handler) {
|
|
|
|
r.notFound = handler
|
|
|
|
}
|