53 lines
1.2 KiB
Go
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)
|
|
}
|
|
}
|