-
Notifications
You must be signed in to change notification settings - Fork 0
/
cors.go
79 lines (65 loc) · 1.68 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
package panurge
import (
"net/http"
"strings"
"github.com/rs/cors"
)
// DefaultCORSDomains returns the default allowed domain suffixes.
func DefaultCORSDomains() []string {
return []string{".infomaker.io", ".navigacloud.com"}
}
// CORSOptions controls the behaviour of the CORS middleware.
type CORSOptions struct {
AllowHTTP bool
AllowedDomains []string
Custom cors.Options
}
// DefaultCorsMiddleware creates a middleware with the default
// settings.
func DefaultCORSMiddleware() *cors.Cors {
return NewCORSMiddleware(CORSOptions{})
}
// NewCORSMiddleware creates a CORS middleware suitable for our
// editorial application APIs.
func NewCORSMiddleware(opts CORSOptions) *cors.Cors {
if len(opts.AllowedDomains) == 0 {
opts.AllowedDomains = DefaultCORSDomains()
}
coreOpts := opts.Custom
if len(coreOpts.AllowedMethods) == 0 {
coreOpts.AllowedMethods = []string{http.MethodPost}
}
allowFn := standardAllowOriginFunc(
opts.AllowHTTP, opts.AllowedDomains,
)
if coreOpts.AllowOriginFunc != nil {
allowFn = anyOfAllowOriginFuncs(coreOpts.AllowOriginFunc, allowFn)
}
coreOpts.AllowOriginFunc = allowFn
return cors.New(coreOpts)
}
func standardAllowOriginFunc(
allowHTTP bool, allowedDomains []string,
) func(origin string) bool {
return func(origin string) bool {
if !allowHTTP && !strings.HasPrefix(origin, "https://") {
return false
}
for _, domain := range allowedDomains {
if strings.HasSuffix(origin, domain) {
return true
}
}
return false
}
}
func anyOfAllowOriginFuncs(funcs ...func(string) bool) func(string) bool {
return func(s string) bool {
for _, fn := range funcs {
if fn(s) {
return true
}
}
return false
}
}