Skip to content

Instantly share code, notes, and snippets.

@pantaluna
Created September 20, 2014 22:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pantaluna/b282171c988e05b9ddab to your computer and use it in GitHub Desktop.
Save pantaluna/b282171c988e05b9ddab to your computer and use it in GitHub Desktop.
func (self *Security) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
// Browser CORS
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
// http://www.html5rocks.com/en/tutorials/cors/
origin := r.Header.Get(mjdlib.HttpHeaderKeyOrigin);
// Browser CORS Origin: a Preflight Request (OPTIONS)
if r.Method == "OPTIONS" {
mjdlib.LogInfo("**CORS OPTIONS URL %v: \n request = %v\n", r.RequestURI, r)
if self.isAllowedCorsOrigin(origin) {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Methods", "POST")
rw.Header().Set("Access-Control-Max-Age", "1000")
rw.Header().Set("Access-Control-Allow-Headers", "X-Api-Key, Accept, Content-Type, Origin, X-Requested-With")
} else {
mjdlib.LogError("**CORS OPTIONS failed \n Bad origin: %v \n request = %v \n", origin, r)
rw.WriteHeader(http.StatusForbidden)
}
return
}
// Browser CORS Origin: a normal Request
if origin != "" {
if self.isAllowedCorsOrigin(origin) {
rw.Header().Set("Access-Control-Allow-Origin", origin)
} else {
mjdlib.LogError("**CORS failed (not the OPTIONS request) \n Bad origin: %v \n request = %v \n", origin, r)
rw.WriteHeader(http.StatusForbidden)
return
}
}
//
// Normal flow: chain the next HTTP middleware
next(rw, r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment