Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created July 6, 2019 02:24
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 xeoncross/8568d76563a279642c36900316444759 to your computer and use it in GitHub Desktop.
Save xeoncross/8568d76563a279642c36900316444759 to your computer and use it in GitHub Desktop.
Simple CORS middleware for Go as a http.Handler
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