搜索好友接口优化

This commit is contained in:
2025-12-14 15:19:24 +08:00
parent b189251a6f
commit 4f2b0bb213
3 changed files with 423 additions and 0 deletions

View File

@@ -0,0 +1,67 @@
/**
* package api
* 作用全局搜索API处理器
*/
package api
import (
"strconv"
"xk-websocket-v2/internal/service"
"xk-websocket-v2/internal/utils"
"github.com/gin-gonic/gin"
)
/**
* GlobalSearchHandler
* 功能:聚合搜索(联系人、群聊、聊天记录)
* 路径GET /api/search?keyword=xxx&type=all|contacts|groups|messages&limit=20
*
* 参数说明:
* - keyword: 搜索关键词(必填)
* - type: 搜索类型可选值all默认、contacts、groups、messages
* - limit: 每类结果的最大数量默认20
*
* 返回结构:
* {
* "contacts": [{ "user": {...}, "remark_name": "xxx", "room_id": "xxx" }],
* "groups": [{ "room_id": "xxx", "room_name": "xxx", ... }],
* "messages": [{ "id": 1, "room_id": "xxx", "content": "xxx", "sender": {...} }]
* }
*/
func GlobalSearchHandler(c *gin.Context) {
// 获取当前用户ID
userID, exists := c.Get("user_id")
if !exists {
utils.Unauthorized(c, "未登录")
return
}
// 获取搜索参数
keyword := c.Query("keyword")
if keyword == "" {
utils.BadRequest(c, "搜索关键词不能为空")
return
}
searchType := c.DefaultQuery("type", "all")
if searchType != "all" && searchType != "contacts" && searchType != "groups" && searchType != "messages" {
searchType = "all"
}
limitStr := c.DefaultQuery("limit", "20")
limit, err := strconv.Atoi(limitStr)
if err != nil || limit <= 0 || limit > 100 {
limit = 20
}
// 执行搜索
result, err := service.SearchSvc.GlobalSearch(userID.(string), keyword, searchType, limit)
if err != nil {
utils.InternalError(c, "搜索失败")
return
}
utils.SuccessWithData(c, result, "搜索成功")
}