Skip to content

Instantly share code, notes, and snippets.

@lukaszx0
Last active April 4, 2018 14:32
Show Gist options
  • Save lukaszx0/556f7594a8c337b745757bf04bb5d680 to your computer and use it in GitHub Desktop.
Save lukaszx0/556f7594a8c337b745757bf04bb5d680 to your computer and use it in GitHub Desktop.
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