Files
ITWorx Pulse release export bd774932d5
Public source validation / validate (push) Failing after 3m8s
Publish ITWorx Pulse source
2026-09-03 02:09:19 +02:00

50 lines
1.4 KiB
Go

package forecastapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/itworx/pulse/internal/auth"
"github.com/itworx/pulse/internal/forecast"
"github.com/itworx/pulse/internal/problem"
)
type Handler struct {
Provider forecast.Provider
}
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/v1/forecasts" {
http.NotFound(w, r)
return
}
if _, ok := auth.PrincipalFromContext(r.Context()); !ok {
problem.Write(w, r, http.StatusUnauthorized, "UNAUTHORIZED", "Authentication required", "Authentication is required to read forecasts.", nil)
return
}
if err := r.Context().Err(); err != nil {
return
}
snapshot, err := h.snapshot(r)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return
}
problem.Write(w, r, http.StatusServiceUnavailable, "FORECASTS_UNAVAILABLE", "Forecastgegevens niet beschikbaar", "De capaciteitsvoorspellingen konden niet worden gelezen.", nil)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "private, max-age=15")
_ = json.NewEncoder(w).Encode(snapshot)
}
func (h Handler) snapshot(r *http.Request) (forecast.Snapshot, error) {
if h.Provider == nil {
return forecast.UnknownSnapshot(time.Now().UTC(), "source_unavailable"), nil
}
return h.Provider.Snapshot(r.Context())
}