feat: 基本广播服务

- 由Hub接收/push/{topic}的请求并解析信息体广播到对应的Client
This commit is contained in:
2025-12-17 14:49:59 +08:00
parent 53555a31c0
commit 1dbcc03e46
16 changed files with 245 additions and 191 deletions

View File

@ -2,25 +2,28 @@ package handler
import (
"encoding/json"
"log"
"net/http"
"time"
"git.jinshen.cn/remilia/push-server/interval/server/api/dto"
"git.jinshen.cn/remilia/push-server/interval/server/model"
"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 := model.Topic(topicStr)
topic := protocol.Topic(topicStr)
if !topic.Valid() {
http.Error(w, "invalid topic", http.StatusBadRequest)
return
}
var req dto.PublishRequest
var req PublishRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
@ -30,12 +33,14 @@ func PushHandler(hub *ws.Hub) http.HandlerFunc {
return
}
msg := model.Message{
Topic: topic,
Content: []byte(req.Content),
Timestamp: time.Now().Unix(),
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