-
Notifications
You must be signed in to change notification settings - Fork 52
/
cors.go
118 lines (103 loc) · 2.51 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package cors
import (
"net/http"
"strings"
"github.com/sohaha/zlsgo/znet"
"github.com/sohaha/zlsgo/zstring"
)
type (
// Config cors configuration
Config struct {
CustomHandler Handler
methods string
credentials string
headers string
exposeHeaders string
Domains []string
Methods []string
Credentials []string
Headers []string
ExposeHeaders []string
}
Handler func(conf *Config, c *znet.Context)
)
const (
DefaultHeaders = "Origin,No-Cache,X-Requested-With,If-Modified-Since,Pragma,Last-Modified,Cache-Control,Expires,Content-Type,Access-Control-Allow-Origin,Authorization"
)
func Default() znet.HandlerFunc {
return New(&Config{})
}
func NewAllowHeaders() (addAllowHeader func(header string), handler znet.HandlerFunc) {
conf := &Config{}
handler = New(conf)
return func(header string) {
conf.headers = conf.headers + ", " + header
}, handler
}
func New(conf *Config) znet.HandlerFunc {
if len(conf.Methods) == 0 {
conf.Methods = []string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodConnect,
http.MethodOptions,
http.MethodTrace,
}
}
conf.methods = strings.Join(conf.Methods, ", ")
if len(conf.Credentials) == 0 {
conf.Credentials = []string{"true"}
}
conf.credentials = strings.Join(conf.Credentials, ", ")
if len(conf.Headers) != 0 {
conf.headers = strings.Join(conf.Headers, ", ")
} else {
conf.headers = DefaultHeaders
}
if len(conf.ExposeHeaders) > 0 {
conf.exposeHeaders = strings.Join(conf.ExposeHeaders, ", ")
}
return func(c *znet.Context) {
if applyCors(c, conf) {
c.Next()
}
}
}
func applyCors(c *znet.Context, conf *Config) bool {
origin := c.GetHeader("Origin")
if len(origin) == 0 {
return true
}
domains := conf.Domains
if len(domains) > 0 {
adopt := false
for k := range domains {
if adopt = zstring.Match(origin, domains[k]); adopt {
break
}
}
if !adopt {
c.Abort(http.StatusForbidden)
return false
}
}
c.SetHeader("Access-Control-Allow-Methods", conf.methods)
c.SetHeader("Access-Control-Allow-Credentials", conf.credentials)
c.SetHeader("Access-Control-Allow-Headers", conf.headers)
if conf.exposeHeaders != "" {
c.SetHeader("Access-Control-Expose-Headers", conf.exposeHeaders)
}
c.SetHeader("Access-Control-Allow-Origin", origin)
if conf.CustomHandler != nil {
conf.CustomHandler(conf, c)
}
if c.Request.Method == "OPTIONS" {
c.Abort(http.StatusNoContent)
return false
}
return true
}