forked from orijtech/otils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcors.go
76 lines (64 loc) · 1.74 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
package otils
import (
"net/http"
)
type CORS struct {
Origins []string
Methods []string
Headers []string
// AllowCredentials when set signifies that the header
// "Access-Control-Allow-Credentials" which will allow
// the possibility of the frontend XHR's withCredentials=true
// to be set.
AllowCredentials bool
next http.Handler
}
func CORSMiddleware(c *CORS, next http.Handler) http.Handler {
if c == nil {
return next
}
copy := new(CORS)
*copy = *c
copy.next = next
return copy
}
var allInclusiveCORS = &CORS{
Origins: []string{"*"},
Methods: []string{"*"},
Headers: []string{"*"},
AllowCredentials: true,
}
// CORSMiddlewareAllInclusive is a convenience helper that uses the
// all inclusive CORS:
// Access-Control-Allow-Origin: *
// Access-Control-Allow-Methods: *
// Access-Control-Allow-Headers: *
// Access-Control-Allow-Credentials: *
// thus enabling all origins, all methods and all headers.
func CORSMiddlewareAllInclusive(next http.Handler) http.Handler {
return CORSMiddleware(allInclusiveCORS, next)
}
var _ http.Handler = (*CORS)(nil)
func (c *CORS) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
c.setCORSForResponseWriter(rw)
if c.next != nil {
c.next.ServeHTTP(rw, req)
}
}
func (c *CORS) setCORSForResponseWriter(rw http.ResponseWriter) {
for _, origin := range c.Origins {
rw.Header().Add("Access-Control-Allow-Origin", origin)
}
for _, mtd := range c.Methods {
rw.Header().Add("Access-Control-Allow-Methods", mtd)
}
for _, hdr := range c.Headers {
rw.Header().Add("Access-Control-Allow-Headers", hdr)
}
if c.AllowCredentials {
rw.Header().Add("Access-Control-Allow-Credentials", "true")
}
}
func unexportedField(name string) bool {
return len(name) > 0 && name[0] >= 'a' && name[0] <= 'z'
}