Refactor handlers package

Fixes #19.
This commit is contained in:
Matthew Dillon 2015-10-13 11:06:02 -07:00
parent 978a6d09b2
commit e756b13099
6 changed files with 279 additions and 248 deletions

27
handlers/cors.go Normal file
View file

@ -0,0 +1,27 @@
package handlers
import (
"net/http"
"os"
"strings"
)
func corsHandler(h http.Handler) http.Handler {
cors := func(w http.ResponseWriter, r *http.Request) {
domains := os.Getenv("DOMAINS")
allowedDomains := strings.Split(domains, ",")
if origin := r.Header.Get("Origin"); origin != "" {
for _, s := range allowedDomains {
if s == origin {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers"))
w.Header().Set("Access-Control-Allow-Methods", r.Header.Get("Access-Control-Request-Method"))
}
}
}
if r.Method != "OPTIONS" {
h.ServeHTTP(w, r)
}
}
return http.HandlerFunc(cors)
}