Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created October 31, 2020 14: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/c967765cac1e04a7afb56a99eeb0d8e4 to your computer and use it in GitHub Desktop.
Save parzibyte/c967765cac1e04a7afb56a99eeb0d8e4 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", "http://localhost")
}).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", "http://localhost")
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