60 lines
1.6 KiB
Go
60 lines
1.6 KiB
Go
package service
|
|
|
|
import (
|
|
"fmt"
|
|
"gitea.bvbej.com/bvbej/base-golang/pkg/websocket/codec"
|
|
_ "gitea.bvbej.com/bvbej/base-golang/pkg/websocket/codec/json"
|
|
"gitea.bvbej.com/bvbej/base-golang/pkg/websocket/peer"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
var (
|
|
serviceLogger *zap.Logger
|
|
|
|
RegisteredServiceList = make(map[string]*Service) // all registered service
|
|
RouterCodec codec.Codec
|
|
)
|
|
|
|
const ChildName = "Hbase"
|
|
|
|
type Hbase any
|
|
|
|
func RegisterService(logger *zap.Logger, comp ...Component) {
|
|
serviceLogger = logger
|
|
for _, v := range comp {
|
|
s := NewService(v)
|
|
if _, ok := RegisteredServiceList[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)
|
|
}
|
|
RegisteredServiceList[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 any) error {
|
|
if RouterCodec == nil {
|
|
return fmt.Errorf("service: codec not set")
|
|
}
|
|
rb, err := RouterCodec.Marshal(router, data, nil)
|
|
if err != nil {
|
|
return fmt.Errorf("service: %v", err)
|
|
}
|
|
return session.Conn.Send(rb)
|
|
}
|