You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.2 KiB

3 years ago
  1. package ws
  2. import (
  3. "github.com/flipped-aurora/ws/core/biz"
  4. "github.com/flipped-aurora/ws/core/data"
  5. "github.com/gin-gonic/gin"
  6. "go.uber.org/zap"
  7. "nhooyr.io/websocket"
  8. )
  9. type wsPlugin struct {
  10. logger *zap.Logger // 日志输出对象
  11. manageBuf int64 // buffer
  12. registeredMsgHandler map[int32]func(biz.IMessage) bool // 消息处理
  13. checkMap map[string]biz.CheckFunc // 用户校验
  14. admin biz.IManage
  15. adminCase *biz.AdminCase
  16. }
  17. func DefaultRegisteredMsgHandler(admin biz.IManage, logger *zap.Logger) map[int32]func(biz.IMessage) bool {
  18. return map[int32]func(msg biz.IMessage) bool{
  19. 1: func(msg biz.IMessage) bool {
  20. // w.admin 里面找到注册客户端的方法
  21. client, ok := admin.FindClient(msg.GetTo())
  22. if !ok {
  23. logger.Info("没有找到该用户")
  24. return false
  25. }
  26. return client.SendMes(msg)
  27. },
  28. }
  29. }
  30. func DefaultCheckMap() map[string]biz.CheckFunc {
  31. return map[string]biz.CheckFunc{
  32. "gva_ws": func(c interface{}) (string, bool) {
  33. // 先断言是gin.content
  34. cc, ok := c.(*gin.Context)
  35. if !ok {
  36. return "", false
  37. }
  38. token := cc.Query("jwt")
  39. // 可以携带jwt
  40. if len(token) == 0 {
  41. return "", false
  42. }
  43. // 解析 jwt...
  44. return token, true
  45. },
  46. }
  47. }
  48. func (w *wsPlugin) Register(g *gin.RouterGroup) {
  49. // gva_ws 为身份校验函数
  50. g.GET("/ws", w.adminCase.HandlerWS("gva_ws", &websocket.AcceptOptions{
  51. InsecureSkipVerify: true,
  52. }))
  53. g.POST("/sendMsg", w.adminCase.SendMsg("gva_ws"))
  54. }
  55. func (w *wsPlugin) RouterPath() string {
  56. return "gva_ws"
  57. }
  58. func GenerateWs(logger *zap.Logger, manageBuf int64, checkMap map[string]biz.CheckFunc) *wsPlugin {
  59. m := data.NewManage(manageBuf)
  60. t := data.NewTopic()
  61. h := data.NewHandle()
  62. admin := data.NewAdmin(m, t, h, logger)
  63. for s, checkFunc := range checkMap {
  64. admin.AddCheckFunc(s, checkFunc)
  65. }
  66. registeredMsgHandler := DefaultRegisteredMsgHandler(admin, logger)
  67. for key, handler := range registeredMsgHandler {
  68. admin.RegisteredMsgHandler(key, handler)
  69. }
  70. return &wsPlugin{logger: logger, manageBuf: manageBuf,
  71. registeredMsgHandler: registeredMsgHandler, checkMap: checkMap, admin: admin, adminCase: biz.NewAdmin(admin)}
  72. }