48 lines
1.1 KiB
Go
48 lines
1.1 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.jinshen.cn/remilia/push-server/interval/api/dto"
|
|
"git.jinshen.cn/remilia/push-server/interval/hub"
|
|
"git.jinshen.cn/remilia/push-server/interval/model"
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
func PushHandler(hub *hub.Hub) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
topicStr := chi.URLParam(r, "topic")
|
|
topic := model.Topic(topicStr)
|
|
if !topic.Valid() {
|
|
http.Error(w, "invalid topic", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
var req dto.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 := model.Message{
|
|
Topic: topic,
|
|
Content: []byte(req.Content),
|
|
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)
|
|
}
|
|
}
|