From 65903bcd2aa7b018c2d87621cea8e8c82ffe32d2 Mon Sep 17 00:00:00 2001 From: Vanesa Date: Sun, 4 Sep 2016 17:43:25 +0200 Subject: [PATCH] allow CORS for api GET and OPTIONS --- api.go | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/api.go b/api.go index 80cadc7b..9544f8cc 100644 --- a/api.go +++ b/api.go @@ -52,6 +52,20 @@ func init() { prometheus.Register(numInvalidAlerts) } +var corsHeaders = map[string]string{ + "Access-Control-Allow-Headers": "Accept, Authorization, Content-Type, Origin", + "Access-Control-Allow-Methods": "GET, OPTIONS", + "Access-Control-Allow-Origin": "*", + "Access-Control-Expose-Headers": "Date", +} + +// Enables cross-site script calls. +func setCORS(w http.ResponseWriter) { + for h, v := range corsHeaders { + w.Header().Set(h, v) + } +} + // API provides registration of handlers for API routes. type API struct { alerts provider.Alerts @@ -82,7 +96,14 @@ func NewAPI(alerts provider.Alerts, silences provider.Silences, gf func() AlertO // Register registers the API handlers under their correct routes // in the given router. func (api *API) Register(r *route.Router) { - ihf := prometheus.InstrumentHandlerFunc + ihf := func(name string, f http.HandlerFunc) http.HandlerFunc { + return prometheus.InstrumentHandlerFunc(name, func(w http.ResponseWriter, r *http.Request) { + setCORS(w) + f(w, r) + }) + } + + r.Options("/*path", ihf("options", func(w http.ResponseWriter, r *http.Request) {})) // Register legacy forwarder for alert pushing. r.Post("/alerts", ihf("legacy_add_alerts", api.legacyAddAlerts))