type Processor interface { OnHandleRequest(req *Request, resp *Response) (int32, error) }
协议号又可以拆分为模块号和命令号。一个模块对应一个Service,该模块下每个命令对应一个Processor,通过map结构做映射
type Service struct { mapCmd2Processor map[uint16]Processor }
func AddProcessor(cmd uint16, p Processor) error
func GetProcessor(cmd uint16) Processor
func RemoveProcessor(cmd uint16) error
func (s *Service) OnHandleRequest(req *Request, resp *Response) (int32, error) { p, ok := s.mapCmd2Processor[req.Cmd] if ok { return p.OnHandleRequest(req, resp) } }
type Server struct { mapMod2Service map[uint16]*Service rpc *Rpc }
func AddService(mod uint16, srv *Service) error func GetService(mod uint16) *Service func RemoveService(mod uint16) error
serv := s.GetService(req.Mod) if serv != nil { code, err := serv.OnHandleRequest(req, resp) }
type ServerAdapter interface { OnRequest(payload []byte) (*Request, error) OnResponse(pack *Response) ([]byte, error) } type Server struct { mapMod2Service map[uint16]*Service rpc *Rpc adapter ServerAdapter }
type Request struct { Mod uint16 Cmd uint16 Payload []byte } type Response struct { Mod uint16 Cmd uint16 Payload []byte }
type Interceptor interface { OnPreHandle(req *Request, resp *Response) (int32, error) OnHandleCompletion(req *Request, resp *Response) (int32, error) OnResponseCompletion(req *Request, resp *Response) error }
type InterceptorList []Interceptor type Server struct { mapMod2Service map[uint16]*Service rpc *Rpc adapter ServerAdapter globalInterceptors InterceptorList mapMod2Interceptors map[uint16]InterceptorList }
// adapter req, err := s.adapter.OnRequest(payload) resp := NewResponse(req) // prehandle interList, ok := s.mapMod2Interceptors[req.Mod] s.prehandle(interList, ok, req, resp) // handle serv := s.GetService(req.Mod) code, err := serv.OnHandleRequest(req, resp) // handle complete s.handleCompletion(interList, ok, req, resp) s.push(resp) // response complete s.responseCompletion(interList, ok, req, resp)
原文:https://www.cnblogs.com/niudanshui/p/15309838.html