register_strategy.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package MessageHandlers
  2. import (
  3. "context"
  4. "github.com/zeromicro/go-zero/core/logx"
  5. "wechat-api/internal/pkg/wechat_ws"
  6. "wechat-api/internal/svc"
  7. )
  8. // MessageHandlerStrategy 消息处理策略接口
  9. type MessageHandlerStrategy interface {
  10. Handle(ctx context.Context, msg *wechat_ws.MsgJsonObject, svcCtx *svc.ServiceContext) error
  11. }
  12. type MessageHandler struct {
  13. strategies map[string]MessageHandlerStrategy
  14. svcCtx *svc.ServiceContext
  15. }
  16. func NewMessageHandler(svcCtx *svc.ServiceContext) *MessageHandler {
  17. return &MessageHandler{
  18. strategies: make(map[string]MessageHandlerStrategy),
  19. svcCtx: svcCtx,
  20. }
  21. }
  22. // RegisterStrategy 注册消息处理策略
  23. func (h *MessageHandler) RegisterStrategy(msgType string, strategy MessageHandlerStrategy) {
  24. h.strategies[msgType] = strategy
  25. }
  26. // Handle 根据 msgType 处理消息
  27. func (h *MessageHandler) Handle(ctx context.Context, msg *wechat_ws.MsgJsonObject) error {
  28. strategy, exists := h.strategies[msg.MsgType]
  29. if !exists {
  30. logx.Error("No handler registered for msgType: %s", msg.MsgType)
  31. return nil
  32. }
  33. return strategy.Handle(ctx, msg, h.svcCtx)
  34. }
  35. // RegisterStrategies 使用映射表注册所有策略
  36. func (h *MessageHandler) RegisterStrategies() {
  37. strategyMap := map[string]func(*svc.ServiceContext) MessageHandlerStrategy{
  38. "FriendPushNotice": func(svcCtx *svc.ServiceContext) MessageHandlerStrategy {
  39. return NewFriendPushNoticeTypeHandler(svcCtx)
  40. },
  41. "ChatroomPushNotice": func(svcCtx *svc.ServiceContext) MessageHandlerStrategy {
  42. return NewChatroomPushNoticeTypeHandler(svcCtx)
  43. },
  44. }
  45. for msgType, strategyFunc := range strategyMap {
  46. h.RegisterStrategy(msgType, strategyFunc(h.svcCtx))
  47. }
  48. }