Created
September 20, 2014 22:15
-
-
Save pantaluna/b282171c988e05b9ddab 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
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