service_manager.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package service
  2. import (
  3. "fmt"
  4. "go.uber.org/zap"
  5. "os"
  6. "git.bvbej.com/bvbej/base-golang/pkg/websocket/codec"
  7. _ "git.bvbej.com/bvbej/base-golang/pkg/websocket/codec/json"
  8. "git.bvbej.com/bvbej/base-golang/pkg/websocket/peer"
  9. )
  10. var serviceList map[string]*Service // all registered service
  11. var routerCodec codec.Codec
  12. var serviceLogger *zap.Logger
  13. const ChildName = "Hbase"
  14. type Hbase interface {
  15. }
  16. func RegisterService(logger *zap.Logger, comp ...Component) {
  17. serviceLogger = logger
  18. for _, v := range comp {
  19. s := NewService(v)
  20. if _, ok := serviceList[s.Name]; ok {
  21. serviceLogger.Sugar().Errorf("service: service already defined: %s", s.Name)
  22. }
  23. if err := s.ExtractHandler(); err != nil {
  24. serviceLogger.Sugar().Errorf("service: extract handler function failed: %v", err)
  25. }
  26. serviceList[s.Name] = s
  27. for name, handler := range s.Handlers {
  28. router := fmt.Sprintf("%s.%s", s.Name, name)
  29. //注册消息 用于解码
  30. codec.RegisterMessage(router, handler.Type)
  31. serviceLogger.Sugar().Debugf("service: router %s param %s registed", router, handler.Type)
  32. }
  33. }
  34. }
  35. func SetCodec(name string) error {
  36. routerCodec = codec.GetCodec(name)
  37. if routerCodec == nil {
  38. return fmt.Errorf("service: codec %s not registered", name)
  39. }
  40. return nil
  41. }
  42. func Send(session *peer.Session, router string, data any) error {
  43. rb, err := routerCodec.Marshal(router, data, nil)
  44. if err != nil {
  45. return fmt.Errorf("service: %v", err)
  46. }
  47. return session.Conn.Send(rb)
  48. }
  49. func init() {
  50. serviceList = make(map[string]*Service)
  51. routerCodec = codec.GetCodec("json_codec")
  52. if routerCodec == nil {
  53. fmt.Println("service: codec json_codec not registered")
  54. os.Exit(1)
  55. }
  56. }