33 lines
851 B
Go
33 lines
851 B
Go
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": "消息发送成功"})
|
||
}
|