Created
July 6, 2019 02:24
-
-
Save xeoncross/8568d76563a279642c36900316444759 to your computer and use it in GitHub Desktop.
Simple CORS middleware for Go as a http.Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func HandlePreFlight(h http.HandlerFunc, methods ...string) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
methods = append(methods, http.MethodOptions) | |
w.Header().Set("Content-Type", "application/json") | |
w.Header().Set("Access-Control-Allow-Credentials", "true") | |
w.Header().Set("Access-Control-Allow-Origin", config.APIAccessControlAllowOriginDomain) | |
w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ", ")) | |
w.Header().Set("Access-Control-Allow-Headers", "Accept, Accept-Endcoding, Content-Type, Content-Length, Authorization, X-CSRF-token") | |
w.Header().Set("Access-Control-Expose-Headers", "Session-Token") | |
if r.Method == http.MethodOptions { | |
return | |
} | |
// Pass on the request. | |
h(w, r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment