From 4580a95b7490bf88cf696ba73c0542ed50f9fa91 Mon Sep 17 00:00:00 2001 From: Mark Beamer Jr Date: Wed, 10 Mar 2021 20:04:48 -0500 Subject: [PATCH 1/2] Add CORS to api server --- extras/api/server.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/extras/api/server.go b/extras/api/server.go index 140603b..151415a 100644 --- a/extras/api/server.go +++ b/extras/api/server.go @@ -17,6 +17,9 @@ import ( // ResponseHeaders are returned with each response var ResponseHeaders map[string]string +// CorsDomains Allowed domains for CORS Policy +var CorsDomains []string + // Log allows logging of events and errors var Log = func(*http.Request, *Response, error) {} @@ -78,6 +81,20 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } + for _, d := range CorsDomains { + if d == r.Header.Get("origin") { + w.Header().Set("Access-Control-Allow-Origin", d) + vary := w.Header().Get("Vary") + if vary != "*" { + if vary != "" { + vary += ", " + } + vary += "Origin" + } + w.Header().Set("Vary", vary) + } + } + // Stop here if its a preflighted OPTIONS request if r.Method == "OPTIONS" { return -- 2.45.2 From d7e84c6b973072c9e034acb457ca225e37e10d8e Mon Sep 17 00:00:00 2001 From: Mark Beamer Jr Date: Wed, 10 Mar 2021 20:55:59 -0500 Subject: [PATCH 2/2] Add CORS to api server configuration --- extras/api/server.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/extras/api/server.go b/extras/api/server.go index 151415a..bc25941 100644 --- a/extras/api/server.go +++ b/extras/api/server.go @@ -20,6 +20,9 @@ var ResponseHeaders map[string]string // CorsDomains Allowed domains for CORS Policy var CorsDomains []string +// CorsAllowLocalhost if true localhost connections are always allowed +var CorsAllowLocalhost bool + // Log allows logging of events and errors var Log = func(*http.Request, *Response, error) {} @@ -80,9 +83,9 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set(key, value) } } - + origin := r.Header.Get("origin") for _, d := range CorsDomains { - if d == r.Header.Get("origin") { + if d == origin { w.Header().Set("Access-Control-Allow-Origin", d) vary := w.Header().Get("Vary") if vary != "*" { @@ -95,6 +98,18 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } + if CorsAllowLocalhost && strings.HasPrefix(origin, "http://localhost:") { + w.Header().Set("Access-Control-Allow-Origin", origin) + vary := w.Header().Get("Vary") + if vary != "*" { + if vary != "" { + vary += ", " + } + vary += "Origin" + } + w.Header().Set("Vary", vary) + } + // Stop here if its a preflighted OPTIONS request if r.Method == "OPTIONS" { return -- 2.45.2