Files
push-server/interval/server/api/handler/push.go
R2m1liA 1dbcc03e46 feat: 基本广播服务
- 由Hub接收/push/{topic}的请求并解析信息体广播到对应的Client
2025-12-17 14:49:59 +08:00

53 lines
1.2 KiB
Go

package handler
import (
"encoding/json"
"log"
"net/http"
"git.jinshen.cn/remilia/push-server/interval/protocol"
"git.jinshen.cn/remilia/push-server/interval/server/ws"
"github.com/go-chi/chi/v5"
)
type PublishRequest struct {
Content string `json:"content"`
}
func PushHandler(hub *ws.Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
topicStr := chi.URLParam(r, "topic")
topic := protocol.Topic(topicStr)
if !topic.Valid() {
http.Error(w, "invalid topic", http.StatusBadRequest)
return
}
var req PublishRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
if req.Content == "" {
http.Error(w, "content cannot be empty", http.StatusBadRequest)
return
}
msg := protocol.BroadcastMessage{
Type: protocol.MsgBroadcast,
Topic: topic,
Payload: json.RawMessage(req.Content),
}
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
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
}
}