From 5c4c8909a96c4d6b4473a8d53443ffbd1787ed67 Mon Sep 17 00:00:00 2001 From: lq Date: Thu, 17 Jul 2025 11:14:38 +0800 Subject: [PATCH] =?UTF-8?q?=E6=A3=80=E6=9F=A5=E7=94=A8=E6=88=B7=E6=98=AF?= =?UTF-8?q?=E5=90=A6=E5=9C=A8=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/websocket_controller.go | 42 ++++++++++++++++++++++++++++++ route/route.go | 1 + 2 files changed, 43 insertions(+) diff --git a/controller/websocket_controller.go b/controller/websocket_controller.go index 997c4f9..7460d63 100644 --- a/controller/websocket_controller.go +++ b/controller/websocket_controller.go @@ -158,6 +158,48 @@ func (c *WebSocketController) HealthHandler(ctx *gin.Context) { }) } +// IsUserOnline 检查某个用户ID是否在线 +func (c *WebSocketController) IsUserOnline(ctx *gin.Context) { + // 优先尝试查询参数,再尝试路径参数 + userID := ctx.Query("user_id") + if userID == "" { + userID = ctx.Param("user_id") + } + + if userID == "" { + ctx.JSON(http.StatusBadRequest, gin.H{ + "code": -1, + "status": "error", + "message": "缺少user_id参数", + }) + return + } + + // 使用与绑定逻辑一致的键名格式 + userClientsKey := fmt.Sprintf("%s:%s", models.UserClientKey, userID) + + // 检查键是否存在并处理错误 + exists, err := c.RedisCli.Exists(c.RedisCtx, userClientsKey).Result() + if err != nil { + log.Printf("⚠️ 检查用户在线状态失败: %v | UserID=%s", err, userID) + ctx.JSON(http.StatusInternalServerError, gin.H{ + "code": -2, + "status": "error", + "message": "服务内部错误", + "result": false, + }) + return + } + + online := exists > 0 + ctx.JSON(http.StatusOK, gin.H{ + "code": 0, + "status": "success", + "message": "请求成功", + "result": online, + }) +} + // HandleWebSocket WebSocket连接处理器 func (c *WebSocketController) HandleWebSocket(ctx *gin.Context) { start := time.Now() diff --git a/route/route.go b/route/route.go index 62e1d82..d9602ad 100644 --- a/route/route.go +++ b/route/route.go @@ -17,6 +17,7 @@ func SetupRoutes(router *gin.Engine, wsCtrl *controller.WebSocketController) { apiGroup.POST("/bind", wsCtrl.BindHandler) apiGroup.POST("/send-to-user", wsCtrl.SendToUserHandler) apiGroup.GET("/health", wsCtrl.HealthHandler) + apiGroup.GET("/check-user-online", wsCtrl.IsUserOnline) // 新增的消息路由 apiGroup.GET("/messages", wsCtrl.GetMessagesHandler)