broadcast/cmd/broadcast/http_handler.go

126 lines
2.7 KiB
Go

package main
import (
"encoding/json"
"net/http"
"git.abbiamoundominio.org/blallo/broadcast"
"git.sr.ht/~blallo/logz/interface"
)
type radioHandler struct {
radio *broadcast.Radio
logger logz.Logger
}
func (h *radioHandler) Start(w http.ResponseWriter, r *http.Request) {
h.logger.Debug(map[string]any{
"msg": "Received Start request",
"context": "http",
})
resp, err := withTimeout(r.Context(), h.radio.Start())
if err != nil {
h.logger.Warn(map[string]any{
"msg": "Failed to start",
"context": "http",
"err": err.Error(),
})
failure(w, http.StatusInternalServerError, map[string]any{
"status": "failed",
"err": err.Error(),
})
return
}
if resp != nil {
h.logger.Warn(map[string]any{
"msg": "Could not start",
"context": "http",
"err": resp.(error).Error(),
})
failure(w, http.StatusInternalServerError, map[string]any{
"status": "failed",
"err": resp.(error).Error(),
})
return
}
success(w, map[string]any{
"status": "success",
})
}
func (h *radioHandler) Stop(w http.ResponseWriter, r *http.Request) {
h.logger.Debug(map[string]any{
"msg": "Received Stop request",
"context": "http",
})
resp, err := withTimeout(r.Context(), h.radio.Stop())
if err != nil {
h.logger.Warn(map[string]any{
"msg": "Failed to stop",
"context": "http",
"err": err.Error(),
})
failure(w, http.StatusInternalServerError, map[string]any{
"status": "failed",
"err": err.Error(),
})
return
}
if resp != nil {
h.logger.Warn(map[string]any{
"msg": "Could not stop",
"context": "http",
"err": resp.(error).Error(),
})
failure(w, http.StatusInternalServerError, map[string]any{
"status": "failed",
"err": resp.(error).Error(),
})
return
}
success(w, map[string]any{
"status": "success",
})
}
func (h *radioHandler) Status(w http.ResponseWriter, r *http.Request) {
h.logger.Debug(map[string]any{
"msg": "Received Status request",
"context": "http",
})
resp, err := withTimeout(r.Context(), h.radio.Status())
if err != nil {
h.logger.Warn(map[string]any{
"msg": "Failed to get status",
"context": "http",
"err": err.Error(),
})
failure(w, http.StatusInternalServerError, map[string]any{
"status": "failed",
"err": err.Error(),
})
return
}
success(w, map[string]any{
"status": "success",
"lines": resp.([]string),
})
}
func success(w http.ResponseWriter, payload map[string]any) {
w.WriteHeader(http.StatusOK)
w.Header().Set("content-type", "application/json")
json.NewEncoder(w).Encode(payload)
}
func failure(w http.ResponseWriter, status int, payload map[string]any) {
w.WriteHeader(status)
w.Header().Set("content-type", "application/json")
json.NewEncoder(w).Encode(payload)
}