55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"time"
|
|
|
|
"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 {
|
|
Payload json.RawMessage `json:"payload"`
|
|
}
|
|
|
|
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
|
|
dec := json.NewDecoder(r.Body)
|
|
dec.DisallowUnknownFields()
|
|
if err := dec.Decode(&req); err != nil {
|
|
http.Error(w, "invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if len(req.Payload) == 0 {
|
|
http.Error(w, "content cannot be empty", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
msg := protocol.BroadcastMessage{
|
|
Type: protocol.MsgBroadcast,
|
|
Topic: topic,
|
|
Payload: req.Payload,
|
|
Timestamp: time.Now().Unix(),
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|