feature(1.2.8): 新增 websocket 模块

- import gorilla/websocket
- 新增 实用工具箱->WebSocket 栏目
This commit is contained in:
新亮
2021-09-20 19:18:15 +08:00
parent 77e8d58298
commit 17be120c06
31 changed files with 848 additions and 19 deletions
@@ -0,0 +1,90 @@
package tool_handler
import (
"encoding/json"
"net/http"
"github.com/xinliangnote/go-gin-api/internal/pkg/code"
"github.com/xinliangnote/go-gin-api/internal/pkg/core"
"github.com/xinliangnote/go-gin-api/internal/pkg/validation"
"github.com/xinliangnote/go-gin-api/internal/websocket/socket_conn/system_message"
"github.com/xinliangnote/go-gin-api/pkg/errno"
"github.com/xinliangnote/go-gin-api/pkg/time_parse"
)
type sendMessageRequest struct {
Message string `form:"message"` // 消息内容
}
type sendMessageResponse struct {
Status string `json:"status"` // 状态
}
// SendMessage 发送消息
// @Summary 发送消息
// @Description 发送消息
// @Tags API.tool
// @Accept multipart/form-data
// @Produce json
// @Param message formData string true "消息内容"
// @Success 200 {object} sendMessageResponse
// @Failure 400 {object} code.Failure
// @Router /api/tool/send_message [post]
func (h *handler) SendMessage() core.HandlerFunc {
type messageBody struct {
Username string `json:"username"`
Message string `json:"message"`
Time string `json:"time"`
}
return func(ctx core.Context) {
req := new(sendMessageRequest)
res := new(sendMessageResponse)
if err := ctx.ShouldBindForm(req); err != nil {
ctx.AbortWithError(errno.NewError(
http.StatusBadRequest,
code.ParamBindError,
validation.Error(err)).WithErr(err),
)
return
}
conn, err := system_message.GetConn()
if err != nil {
ctx.AbortWithError(errno.NewError(
http.StatusBadRequest,
code.SocketConnectError,
code.Text(code.SocketConnectError)).WithErr(err),
)
return
}
messageData := new(messageBody)
messageData.Username = ctx.UserName()
messageData.Message = req.Message
messageData.Time = time_parse.CSTLayoutString()
messageJsonData, err := json.Marshal(messageData)
if err != nil {
ctx.AbortWithError(errno.NewError(
http.StatusBadRequest,
code.SocketSendError,
code.Text(code.SocketSendError)).WithErr(err),
)
return
}
err = conn.OnSend(messageJsonData)
if err != nil {
ctx.AbortWithError(errno.NewError(
http.StatusBadRequest,
code.SocketSendError,
code.Text(code.SocketSendError)).WithErr(err),
)
return
}
res.Status = "OK"
ctx.Payload(res)
}
}
@@ -49,6 +49,11 @@ type Handler interface {
// @Tags API.tool
// @Router /api/tool/data/mysql [post]
SearchMySQL() core.HandlerFunc
// SendMessage 发送消息
// @Tags API.tool
// @Router /api/tool/send_message [post]
SendMessage() core.HandlerFunc
}
type handler struct {