package service import ( "fmt" "go.uber.org/zap" "os" "git.bvbej.com/bvbej/base-golang/pkg/websocket/codec" _ "git.bvbej.com/bvbej/base-golang/pkg/websocket/codec/json" "git.bvbej.com/bvbej/base-golang/pkg/websocket/peer" ) var serviceList map[string]*Service // all registered service var routerCodec codec.Codec var serviceLogger *zap.Logger const ChildName = "Hbase" type Hbase interface { } func RegisterService(logger *zap.Logger, comp ...Component) { serviceLogger = logger for _, v := range comp { s := NewService(v) if _, ok := serviceList[s.Name]; ok { serviceLogger.Sugar().Errorf("service: service already defined: %s", s.Name) } if err := s.ExtractHandler(); err != nil { serviceLogger.Sugar().Errorf("service: extract handler function failed: %v", err) } serviceList[s.Name] = s for name, handler := range s.Handlers { router := fmt.Sprintf("%s.%s", s.Name, name) //注册消息 用于解码 codec.RegisterMessage(router, handler.Type) serviceLogger.Sugar().Debugf("service: router %s param %s registed", router, handler.Type) } } } func SetCodec(name string) error { routerCodec = codec.GetCodec(name) if routerCodec == nil { return fmt.Errorf("service: codec %s not registered", name) } return nil } func Send(session *peer.Session, router string, data interface{}) error { rb, err := routerCodec.Marshal(router, data, nil) if err != nil { return fmt.Errorf("service: %v", err) } return session.Conn.Send(rb) } func init() { serviceList = make(map[string]*Service) routerCodec = codec.GetCodec("json_codec") if routerCodec == nil { fmt.Println("service: codec json_codec not registered") os.Exit(1) } }