Skip to content

Commit

Permalink
exhttp: add CORS helpers
Browse files Browse the repository at this point in the history
Signed-off-by: Sumner Evans <[email protected]>
  • Loading branch information
sumnerevans committed Aug 23, 2024
1 parent 7ddfdc9 commit 851eefa
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions exhttp/cors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
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")
}

// CORSMiddleware adds CORS headers to the response and handles OPTIONS
// requests by returning 200 OK immediately.
func CORSMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
AddCORSHeaders(w)
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}

0 comments on commit 851eefa

Please sign in to comment.