From 78a4580eade1ce915797fb8cab48804f66935a6e Mon Sep 17 00:00:00 2001 From: Alex Ellis Date: Tue, 28 Nov 2017 20:26:42 +0000 Subject: [PATCH] Allow CORS to GitHub raw Signed-off-by: Alex Ellis --- gateway/handlers/cors.go | 24 ++++++++++++++++++++++++ gateway/server.go | 7 ++++++- 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 gateway/handlers/cors.go diff --git a/gateway/handlers/cors.go b/gateway/handlers/cors.go new file mode 100644 index 00000000..ab959a66 --- /dev/null +++ b/gateway/handlers/cors.go @@ -0,0 +1,24 @@ +package handlers + +import "net/http" + +type CorsHandler struct { + Upstream *http.Handler + AllowedHost string +} + +func (c CorsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // https://raw.githubusercontent.com/openfaas/store/master/store.json + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + w.Header().Set("Access-Control-Allow-Methods", "GET") + w.Header().Set("Access-Control-Allow-Origin", c.AllowedHost) + + (*c.Upstream).ServeHTTP(w, r) +} + +func DecorateWithCORS(upstream http.Handler, allowedHost string) http.Handler { + return CorsHandler{ + Upstream: &upstream, + AllowedHost: allowedHost, + } +} diff --git a/gateway/server.go b/gateway/server.go index 3b0780e0..6b4f96e9 100644 --- a/gateway/server.go +++ b/gateway/server.go @@ -143,7 +143,12 @@ func main() { } fs := http.FileServer(http.Dir("./assets/")) - r.PathPrefix("/ui/").Handler(http.StripPrefix("/ui", fs)).Methods("GET") + + // This URL allows access from the UI to the OpenFaaS store + allowedCORSHost := "raw.githubusercontent.com" + fsCORS := internalHandlers.DecorateWithCORS(fs, allowedCORSHost) + + r.PathPrefix("/ui/").Handler(http.StripPrefix("/ui", fsCORS)).Methods("GET") r.HandleFunc("/", faasHandlers.RoutelessProxy).Methods("POST")