检查用户是否在线

This commit is contained in:
2025-07-17 11:14:38 +08:00
parent b2c02c1db3
commit 5c4c8909a9
2 changed files with 43 additions and 0 deletions

View File

@@ -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()