-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcors.go
82 lines (64 loc) · 1.73 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package elephantine
import (
"fmt"
"net/http"
"net/url"
"strings"
)
type CORSOptions struct {
AllowInsecure bool
AllowInsecureLocalhost bool
Hosts []string
AllowedMethods []string
AllowedHeaders []string
MaxAgeSeconds int
}
func CORSMiddleware(opts CORSOptions, handler http.Handler) http.Handler {
if opts.MaxAgeSeconds == 0 {
opts.MaxAgeSeconds = 3600
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
accessMethod := r.Header.Get("Access-Control-Request-Method")
origin := r.Header.Get("Origin")
header := w.Header()
if r.Method == http.MethodOptions && accessMethod != "" {
if !validOrigin(origin, opts) {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
header.Set("Access-Control-Allow-Methods",
strings.Join(opts.AllowedMethods, ","))
header.Set("Access-Control-Allow-Headers",
strings.Join(opts.AllowedHeaders, ","))
header.Set("Access-Control-Allow-Origin",
origin)
header.Set("Access-Control-Max-Age",
fmt.Sprintf("%d", opts.MaxAgeSeconds))
w.WriteHeader(http.StatusNoContent)
return
}
if origin != "" && validOrigin(origin, opts) {
header.Set("Access-Control-Allow-Origin", origin)
header.Set("Vary", "Origin")
}
handler.ServeHTTP(w, r)
})
}
func validOrigin(origin string, opts CORSOptions) bool {
oURL, err := url.Parse(origin)
if err != nil {
return false
}
allowInsec := opts.AllowInsecure ||
(oURL.Hostname() == "localhost" && opts.AllowInsecureLocalhost)
if !allowInsec && oURL.Scheme != "https" {
return false
}
host := oURL.Hostname()
for _, h := range opts.Hosts {
if host == h || strings.HasSuffix(host, "."+h) {
return true
}
}
return false
}