Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: custom msg handler #33

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion websocket/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func (c *Client) New(session dto.Session) websocket.WebSocket {
session: &session,
closeChan: make(closeErrorChan, 10),
heartBeatTicker: time.NewTicker(60 * time.Second), // 先给一个默认 ticker,在收到 hello 包之后,会 reset
msgHandler: event.ParseAndHandle,
}
}

Expand All @@ -44,11 +45,16 @@ type Client struct {
user *dto.WSUser
closeChan closeErrorChan
heartBeatTicker *time.Ticker // 用于维持定时心跳
msgHandler func(payload *dto.WSPayload) error
}

type messageChan chan *dto.WSPayload
type closeErrorChan chan error

func (c *Client) SetMsgHandler(handler func(payload *dto.WSPayload) error) {
c.msgHandler = handler
}

// Connect 连接到 websocket
func (c *Client) Connect() error {
if c.session.URL == "" {
Expand Down Expand Up @@ -218,7 +224,7 @@ func (c *Client) listenMessageAndHandle() {
continue
}
// 解析具体事件,并投递给业务注册的 handler
if err := event.ParseAndHandle(payload); err != nil {
if err := c.msgHandler(payload); err != nil {
log.Errorf("%s parseAndHandle failed, %v", c.session, err)
}
}
Expand Down
2 changes: 2 additions & 0 deletions websocket/iface.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
type WebSocket interface {
// New 创建一个新的ws实例,需要传递 session 对象
New(session dto.Session) WebSocket
// SetMsgHandler 设置消息处理回调
SetMsgHandler(handler func(payload *dto.WSPayload) error)
// Connect 连接到 wss 地址
Connect() error
// Identify 鉴权连接
Expand Down