添加向特定用户发送信息功能

This commit is contained in:
2025-08-11 15:35:52 +08:00
parent ba655a6aba
commit 23592df471
4 changed files with 150 additions and 26 deletions

View File

@@ -0,0 +1,32 @@
package system
import (
"encoding/json"
"github.com/gin-gonic/gin"
"net/http"
"toutoukan/model/systemmodel"
"toutoukan/socket"
)
func SendMsg(c *gin.Context) {
var req systemmodel.MsgSend
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
// 1. 将Msg结构体序列化为JSON字符串
msgJson, err := json.Marshal(req.Msg)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "消息序列化失败:" + err.Error()})
return
}
// 2. 将JSON字符串转换为[]byte传给SendToUser
err = socket.SendToUser(req.Username, msgJson)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "发送消息失败:" + err.Error()})
return
}
// 发送成功的响应
c.JSON(http.StatusOK, gin.H{"code": 200, "message": "消息发送成功"})
}