channel_api.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package gateway
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "realtime-gateway/internal/channel"
  6. )
  7. type createChannelRequest struct {
  8. Label string `json:"label"`
  9. DeliveryMode string `json:"deliveryMode"`
  10. TTLSeconds int `json:"ttlSeconds"`
  11. }
  12. func (s *Server) registerChannelRoutes(mux *http.ServeMux) {
  13. mux.HandleFunc("/api/channel/create", s.handleCreateChannel)
  14. mux.HandleFunc("/api/admin/channels", s.handleAdminChannels)
  15. }
  16. func (s *Server) handleCreateChannel(w http.ResponseWriter, r *http.Request) {
  17. if r.Method != http.MethodPost {
  18. writeJSON(w, http.StatusMethodNotAllowed, map[string]any{
  19. "error": "method not allowed",
  20. })
  21. return
  22. }
  23. var request createChannelRequest
  24. if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
  25. writeJSON(w, http.StatusBadRequest, map[string]any{
  26. "error": "invalid json body",
  27. })
  28. return
  29. }
  30. created, err := s.channels.Create(channel.CreateRequest{
  31. Label: request.Label,
  32. DeliveryMode: request.DeliveryMode,
  33. TTLSeconds: request.TTLSeconds,
  34. })
  35. if err != nil {
  36. writeJSON(w, http.StatusInternalServerError, map[string]any{
  37. "error": err.Error(),
  38. })
  39. return
  40. }
  41. writeJSON(w, http.StatusOK, created)
  42. }
  43. func (s *Server) handleAdminChannels(w http.ResponseWriter, _ *http.Request) {
  44. items := s.channels.List()
  45. writeJSON(w, http.StatusOK, map[string]any{
  46. "items": items,
  47. "count": len(items),
  48. })
  49. }