fix: 解决json无法正常解析的问题

This commit is contained in:
2025-12-17 15:54:26 +08:00
parent 1dbcc03e46
commit 36296b6af4
5 changed files with 25 additions and 22 deletions

View File

@ -2,8 +2,8 @@ package handler
import (
"encoding/json"
"log"
"net/http"
"time"
"git.jinshen.cn/remilia/push-server/interval/protocol"
"git.jinshen.cn/remilia/push-server/interval/server/ws"
@ -11,7 +11,7 @@ import (
)
type PublishRequest struct {
Content string `json:"content"`
Payload json.RawMessage `json:"payload"`
}
func PushHandler(hub *ws.Hub) http.HandlerFunc {
@ -24,23 +24,25 @@ func PushHandler(hub *ws.Hub) http.HandlerFunc {
}
var req PublishRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&req); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
if req.Content == "" {
if len(req.Payload) == 0 {
http.Error(w, "content cannot be empty", http.StatusBadRequest)
return
}
msg := protocol.BroadcastMessage{
Type: protocol.MsgBroadcast,
Topic: topic,
Payload: json.RawMessage(req.Content),
Type: protocol.MsgBroadcast,
Topic: topic,
Payload: req.Payload,
Timestamp: time.Now().Unix(),
}
log.Printf("Received push request for topic %s: %s", topic, req.Content)
if err := hub.BroadcastMessage(r.Context(), msg); err != nil {
http.Error(w, "request cancelled", http.StatusRequestTimeout)
return

View File

@ -14,7 +14,7 @@ import (
type Client struct {
ID string
Conn *websocket.Conn
SendChan chan []byte
SendChan chan protocol.BroadcastMessage
Hub *Hub
Ctx context.Context
@ -29,7 +29,7 @@ func NewClient(id string, conn *websocket.Conn, hub *Hub, parentCtx context.Cont
return &Client{
ID: id,
Conn: conn,
SendChan: make(chan []byte, 32),
SendChan: make(chan protocol.BroadcastMessage, 32),
Hub: hub,
Ctx: ctx,
@ -49,7 +49,7 @@ func (c *Client) ReadLoop() {
if websocket.CloseStatus(err) == websocket.StatusNormalClosure {
log.Println("WebSocket closed normally:", err)
} else {
log.Println("WebSocket read error:", err)
log.Println("[Server Client.ReadLoop] WebSocket read error:", err)
}
return
}
@ -76,9 +76,10 @@ func (c *Client) WriteLoop() {
if !ok {
return
}
log.Printf("Sending message to client %s: %+v", c.ID, msg)
err := wsjson.Write(c.Ctx, c.Conn, msg)
if err != nil {
log.Println("WebSocket write error:", err)
log.Println("[Server Client.WriteLoop] WebSocket write error:", err)
return
}
}

View File

@ -159,8 +159,8 @@ func (h *Hub) onBroadcast(msg protocol.BroadcastMessage) {
log.Printf("Receiving message for topic %s: %s", msg.Topic, string(msg.Payload))
for _, c := range h.clientsByTopic[msg.Topic] {
select {
case c.SendChan <- msg.Payload:
log.Printf("Sending message to client %s: %s", c.ID, string(msg.Payload))
case c.SendChan <- msg:
log.Printf("[%d] Sending message to client %s: [%s] %v", msg.Timestamp, c.ID, msg.Type, string(msg.Payload))
default:
h.UnregisterClient(c)
if c.Conn != nil {