-
Notifications
You must be signed in to change notification settings - Fork 1
/
cors.go
93 lines (78 loc) · 2.15 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
package middleware
import (
"net/http"
"regexp"
"strings"
"github.com/go-zoox/zoox"
)
// CorsConfig is the configuration for the CORS middleware.
type CorsConfig struct {
IgnoreFunc func(ctx *zoox.Context) bool
AllowOrigins []string
AllowOriginFunc func(origin string) bool
AllowMethods []string
AllowHeaders []string
AllowCredentials bool
ExposeHeaders []string
}
// DefaultCorsConfig is the default CORS configuration.
func DefaultCorsConfig() *CorsConfig {
return &CorsConfig{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization"},
AllowCredentials: true,
ExposeHeaders: []string{},
}
}
// CORS is a middleware for handling CORS (Cross-Origin Resource Sharing)
func CORS(cfg ...*CorsConfig) zoox.Middleware {
cfgX := DefaultCorsConfig()
if len(cfg) > 0 {
cfgX = cfg[0]
}
return func(ctx *zoox.Context) {
origin := ctx.Origin()
isIgnored := false
if cfgX.IgnoreFunc != nil {
isIgnored = cfgX.IgnoreFunc(ctx)
}
isPreflight := ctx.Method == http.MethodOptions
if !isPreflight || isIgnored {
if len(cfgX.ExposeHeaders) > 0 {
ctx.Set("Access-Control-Expose-Headers", strings.Join(cfgX.ExposeHeaders, ","))
}
ctx.Next()
return
}
if cfgX.AllowOriginFunc != nil {
if !cfgX.AllowOriginFunc(origin) {
ctx.Status(http.StatusNoContent)
return // skip
}
} else if len(cfgX.AllowOrigins) > 0 {
var matched bool
var err error
for _, allowOrigin := range cfgX.AllowOrigins {
if matched, err = regexp.MatchString(allowOrigin, origin); err == nil && matched {
break
}
}
if !matched {
ctx.Status(http.StatusNoContent)
return // skip
}
}
ctx.Set("Access-Control-Allow-Origin", origin)
if len(cfgX.AllowMethods) > 0 {
ctx.Set("Access-Control-Allow-Methods", strings.Join(cfgX.AllowMethods, ","))
}
if len(cfgX.AllowHeaders) > 0 {
ctx.Set("Access-Control-Allow-Headers", strings.Join(cfgX.AllowHeaders, ","))
}
if cfgX.AllowCredentials {
ctx.Set("Access-Control-Allow-Credentials", "true")
}
ctx.Next()
}
}