This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
package networkapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/itworx/pulse/internal/auth"
|
||||
"github.com/itworx/pulse/internal/network"
|
||||
"github.com/itworx/pulse/internal/problem"
|
||||
)
|
||||
|
||||
type Handler struct{ Provider network.Provider }
|
||||
|
||||
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/api/v1/network" {
|
||||
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 network health.", nil)
|
||||
return
|
||||
}
|
||||
if err := r.Context().Err(); err != nil {
|
||||
return
|
||||
}
|
||||
if h.Provider == nil {
|
||||
problem.Write(w, r, http.StatusServiceUnavailable, "NETWORK_UNAVAILABLE", "Network health not available", "De netwerkgezondheid is niet beschikbaar.", nil)
|
||||
return
|
||||
}
|
||||
snapshot, err := h.Provider.Snapshot(r.Context())
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return
|
||||
}
|
||||
problem.Write(w, r, http.StatusServiceUnavailable, "NETWORK_UNAVAILABLE", "Network health not available", "De netwerkgezondheid kon niet worden gelezen.", nil)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "private, max-age=5")
|
||||
_ = json.NewEncoder(w).Encode(snapshot)
|
||||
}
|
||||
Reference in New Issue
Block a user