/
cors.go
54 lines (47 loc) · 1.92 KB
/
cors.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package cors
import (
"net/http"
"strings"
"github.com/golang/glog"
)
// AllowCORSFrom adds preflight headers allowing the given origins.
func AllowCORSFrom(h http.Handler, allowedOrigins []string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
for _, allowedOrigin := range allowedOrigins {
if origin == allowedOrigin {
preflightHandler(w, r)
return
}
}
}
}
h.ServeHTTP(w, r)
})
}
// AllowAllCORSFromEverywhere allows Cross Origin Resoruce Sharing from any origin.
// Don't do this without consideration in production systems.
func AllowAllCORSFromEverywhere(h http.Handler, additionalAllowedHeaders ...string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
preflightHandler(w, r, additionalAllowedHeaders...)
return
}
}
h.ServeHTTP(w, r)
})
}
// preflightHandler adds the necessary headers in order to serve
// CORS from any origin using the methods "GET", "HEAD", "POST", "PUT", "DELETE"
// We insist, don't do this without consideration in production systems.
func preflightHandler(w http.ResponseWriter, r *http.Request, additionalAllowedHeaders ...string) {
headers := []string{"Content-Type", "Accept", "Authorization"}
w.Header().Set("Access-Control-Allow-Headers", strings.Join(append(headers, additionalAllowedHeaders...), ","))
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)
}