aqi/ws/dispatcher.go
ideaa 920268c632 feat: add recovery middleware and use negative error codes for system errors
- Added a new recovery middleware
- Use the negative error codes.
2024-06-21 12:14:06 +08:00

64 lines
1.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package ws
import (
"time"
"github.com/tidwall/gjson"
)
func Dispatcher(c *Client, request string) {
t := time.Now()
//ping直接回应
action := gjson.Get(request, "action").String()
if action == "ping" {
c.LastHeartbeatTime = t
c.SendRawMsg(0, "ping", "pong", nil)
return
}
//是否被禁言
if c.User != nil {
isBanned, bandTime := c.User.IsBanned()
if isBanned {
c.SendRawMsg(-11, "sys.ban", "You have been ban", bandTime)
return
}
}
//请求频率限制5毫秒
if t.Sub(c.LastRequestTime).Microseconds() <= 5 {
c.SendRawMsg(-13, "sys.requestLimit", "Your requests are too frequent", nil)
return
} else {
//更新最后请求时间
c.LastRequestTime = t
//如果心跳时间为0设置为当前时间
//防止在连接瞬间被哨兵扫描而断开
if c.LastHeartbeatTime.IsZero() {
c.LastHeartbeatTime = t
}
}
handlers := InitManager().Handlers(action)
if handlers == nil || len(handlers) == 0 {
c.SendRawMsg(-15, action, "Request not supported", nil)
return
}
ctx := &Context{
Client: c,
Action: action,
Params: gjson.Get(request, "params").String(),
Server: wss,
handlers: handlers,
language: "zh",
defaultLng: "zh",
}
ctx.handlers[0](ctx)
ctx.Next()
}