go-proxy/api/router.go

63 lines
1.9 KiB
Go
Raw Normal View History

// Package api mounts the monitoring endpoints on an HTTP mux.
//
// mux := http.NewServeMux()
// api.RegisterRoutes(mux, proxyInstance)
package api
import (
"encoding/json"
"net/http"
"dappco.re/go/proxy"
)
// RouteRegistrar accepts HTTP handler registrations.
//
// mux := http.NewServeMux()
// api.RegisterRoutes(mux, proxyInstance)
type RouteRegistrar interface {
HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
}
// mux := http.NewServeMux()
// api.RegisterRoutes(mux, proxyInstance)
// _ = mux
//
// The mounted routes are GET /1/summary, /1/workers, and /1/miners.
func RegisterRoutes(router RouteRegistrar, p *proxy.Proxy) {
if router == nil || p == nil {
return
}
registerJSONGetRoute(router, p, proxy.MonitoringRouteSummary, func() any { return p.SummaryDocument() })
registerJSONGetRoute(router, p, proxy.MonitoringRouteWorkers, func() any { return p.WorkersDocument() })
registerJSONGetRoute(router, p, proxy.MonitoringRouteMiners, func() any { return p.MinersDocument() })
}
func registerJSONGetRoute(router RouteRegistrar, proxyInstance *proxy.Proxy, pattern string, renderDocument func() any) {
router.HandleFunc(pattern, func(w http.ResponseWriter, request *http.Request) {
if status, ok := allowMonitoringRequest(proxyInstance, request); !ok {
switch status {
case http.StatusMethodNotAllowed:
w.Header().Set("Allow", http.MethodGet)
case http.StatusUnauthorized:
w.Header().Set("WWW-Authenticate", "Bearer")
}
w.WriteHeader(status)
return
}
writeJSON(w, renderDocument())
})
}
func allowMonitoringRequest(proxyInstance *proxy.Proxy, request *http.Request) (int, bool) {
if proxyInstance == nil {
return http.StatusServiceUnavailable, false
}
return proxyInstance.AllowMonitoringRequest(request)
}
func writeJSON(w http.ResponseWriter, payload any) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(payload)
}