Files
nl-im-service/internal/api/search_handler.go
2025-12-14 15:19:24 +08:00

68 lines
1.7 KiB
Go
Raw 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 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, "搜索成功")
}