-
Notifications
You must be signed in to change notification settings - Fork 0
/
cors.go
84 lines (71 loc) · 1.99 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
package tools
import (
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
type (
CorsConfig struct {
AllowOrigins []string
AllowAnyOrigin bool
AllowMethods []string
AllowHeaders []string
AllowCredentials bool
}
)
var (
DefaultAllowHeaders = []string{"authorization", "token", "content-type", "x-requested-with"}
DefaultAllowMethods = []string{http.MethodPost, http.MethodGet, http.MethodPut, http.MethodDelete, http.MethodOptions, http.MethodPatch}
)
func DefaultCorsConfig() *CorsConfig {
return &CorsConfig{
AllowOrigins: []string{"*"},
AllowAnyOrigin: false,
AllowCredentials: true,
AllowHeaders: DefaultAllowHeaders,
AllowMethods: DefaultAllowMethods,
}
}
func DefaultCors(c *gin.Context) {
Cors(c, DefaultCorsConfig())
}
//Cors 自己尝试的cors配置实现
func Cors(c *gin.Context, config *CorsConfig) {
req := c.Request
origin := c.Request.Header.Get("Origin")
if len(origin) == 0 {
// request is not a CORS request
return
}
// host := c.Request.Host
// if origin == "http://"+host || origin == "https://"+host {
// // request is not a CORS request but have origin header.
// // for example, use fetch api
// return
// }
allowOrigins := []string{"*"}
if len(config.AllowOrigins) > 0 {
allowOrigins = config.AllowOrigins
}
// 如果请求的域名在放行名单中
inAllow := 0
for i, o := range allowOrigins {
if origin == o || o == "*" {
inAllow = i + 1
}
}
// 如果在名单中 且 没有开放任意域名通过
if inAllow == 0 && !config.AllowAnyOrigin {
c.AbortWithStatus(http.StatusForbidden)
return
}
// set header
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Access-Control-Allow-Methods", strings.Join(config.AllowMethods, ","))
c.Header("Access-Control-Allow-Credentials", strconv.FormatBool(config.AllowCredentials))
c.Header("Access-Control-Allow-Headers", strings.Join(config.AllowHeaders, ","))
if req.Method == http.MethodOptions {
c.Status(http.StatusNoContent)
}
}