From 41a79613d3c28cb75bd1fbcee564c389ca7b5435 Mon Sep 17 00:00:00 2001 From: Sumner Evans Date: Fri, 23 Aug 2024 15:43:56 -0600 Subject: [PATCH] exhttp: add CORS helpers Signed-off-by: Sumner Evans --- exhttp/cors.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 exhttp/cors.go diff --git a/exhttp/cors.go b/exhttp/cors.go new file mode 100644 index 0000000..aab0138 --- /dev/null +++ b/exhttp/cors.go @@ -0,0 +1,20 @@ +package exhttp + +import "net/http" + +func AddCORSHeaders(w http.ResponseWriter) { + // Recommended CORS headers can be found in https://spec.matrix.org/v1.3/client-server-api/#web-browser-clients + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") + w.Header().Set("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization") + w.Header().Set("Content-Security-Policy", "sandbox; default-src 'none'; script-src 'none'; plugin-types application/pdf; style-src 'unsafe-inline'; object-src 'self';") + // Allow browsers to cache above for 1 day + w.Header().Set("Access-Control-Max-Age", "86400") +} + +func CORSMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + AddCORSHeaders(w) + next.ServeHTTP(w, r) + }) +}