Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created October 12, 2020 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/e7a4ced5286ed97fd21d3dd64a30a666 to your computer and use it in GitHub Desktop.
Save parzibyte/e7a4ced5286ed97fd21d3dd64a30a666 to your computer and use it in GitHub Desktop.
func enableCORS(router *mux.Router) {
router.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", AllowedCORSDomain)
}).Methods(http.MethodOptions)
router.Use(middlewareCors)
}
func middlewareCors(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, req *http.Request) {
// Just put some headers to allow CORS...
w.Header().Set("Access-Control-Allow-Origin", AllowedCORSDomain)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
// and call next handler!
next.ServeHTTP(w, req)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment