-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmiddleware_cors.go
65 lines (55 loc) · 1.82 KB
/
middleware_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
package gin
import (
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/rs/cors"
)
func Cors() http.Middleware {
return func(ctx http.Context) {
path := ctx.Request().Path()
corsPaths, ok := ConfigFacade.Get("cors.paths").([]string)
if !ok {
ctx.Request().Next()
return
}
needCors := false
for _, corsPath := range corsPaths {
corsPath = pathToGinPath(corsPath)
if strings.HasSuffix(corsPath, "*") {
corsPath = strings.ReplaceAll(corsPath, "*", "")
if corsPath == "" || strings.HasPrefix(strings.TrimPrefix(path, "/"), strings.TrimPrefix(corsPath, "/")) {
needCors = true
break
}
} else {
if strings.TrimPrefix(path, "/") == strings.TrimPrefix(corsPath, "/") {
needCors = true
break
}
}
}
if !needCors {
ctx.Request().Next()
return
}
allowedMethods := ConfigFacade.Get("cors.allowed_methods").([]string)
if len(allowedMethods) == 1 && allowedMethods[0] == "*" {
allowedMethods = []string{http.MethodGet, http.MethodPost, http.MethodHead, http.MethodPut, http.MethodDelete, http.MethodPatch}
}
instance := cors.New(cors.Options{
AllowedMethods: allowedMethods,
AllowedOrigins: ConfigFacade.Get("cors.allowed_origins").([]string),
AllowedHeaders: ConfigFacade.Get("cors.allowed_headers").([]string),
ExposedHeaders: ConfigFacade.Get("cors.exposed_headers").([]string),
MaxAge: ConfigFacade.GetInt("cors.max_age"),
AllowCredentials: ConfigFacade.GetBool("cors.supports_credentials"),
AllowPrivateNetwork: true,
})
instance.HandlerFunc(ctx.Response().Writer(), ctx.Request().Origin())
if ctx.Request().Origin().Method == http.MethodOptions &&
ctx.Request().Header("Access-Control-Request-Method") != "" {
ctx.Request().Abort(http.StatusNoContent)
}
ctx.Request().Next()
}
}