Last active
April 4, 2018 14:32
-
-
Save lukaszx0/556f7594a8c337b745757bf04bb5d680 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package utils | |
import ( | |
"net/http" | |
"strings" | |
"github.com/golang/glog" | |
) | |
func AllowCORS(h http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
origin := r.Header.Get("Origin") | |
if origin == "" { | |
return | |
} | |
w.Header().Set("Access-Control-Allow-Origin", origin) | |
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" { | |
preflightHandler(w, r) | |
return | |
} | |
h.ServeHTTP(w, r) | |
}) | |
} | |
func preflightHandler(w http.ResponseWriter, r *http.Request) { | |
headers := []string{"Content-Type", "Accept"} | |
w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ",")) | |
methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"} | |
w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ",")) | |
glog.Infof("preflight request for %s", r.URL.Path) | |
return | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment