-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware_cors.go
67 lines (61 loc) · 2.38 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
66
67
package ginKit
import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"time"
)
// NewCorsMiddleware 新建一个cors中间件.
/*
「Go框架」 Gin 怎么实现允许前端跨域请求?
https://mp.weixin.qq.com/s/2eJUJKJ3Xu5jOYXAfknqtA
@param origins (0) 可以为nil
(1) origin白名单
(2) 支持wildcard(*)
(3) len(origins) == 0,则通配(请求的origin是什么就允许什么)
e.g.
传参: []string{"https://*.github.com", "https://api.*", "http://*", "https://facebook.com", "*.golang.org"}
*/
func NewCorsMiddleware(origins []string) gin.HandlerFunc {
/*
CORS 中间件提供三个函数,代表三种使用方式,分别是:
cors.New()
cors.Default()
cors.DefaultConfig()
*/
config := cors.Config{
// 允许的请求方式,默认值是 GET,POST,PUT,PATCH,DELETE,HEAD,和 OPTIONS
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
// 用在对预请求的响应中,指示实际的请求中可以使用哪些 HTTP 请求头
AllowHeaders: []string{"Content-Type", "Content-Length", "Authorization", "Accept", "Origin", "X-Requested-With"},
// 可以在响应中显示的请求头
ExposeHeaders: []string{"Content-Length", "Content-Type", "Last-Modified"},
// 预请求的结果能被缓存多久
MaxAge: time.Hour * 12,
// 添加请求源是否允许使用通配符,例如 http://some-domain/*,https://api. 或 http://some.*.subdomain.com
AllowWildcard: true,
// 表示请求附带请求凭据时是否响应请求,例如 cookie、HTTP authentication 或客户端 SSL 证书
AllowCredentials: true,
// 允许使用常用的浏览器的扩展模式
AllowBrowserExtensions: true,
// 允许使用 WebSocket 协议
AllowWebSockets: true,
// 允许使用 file:// 协议
AllowFiles: false,
}
if len(origins) > 0 {
/*
(1) 允许部分origin
AllowOrigins: 指定允许请求源的列表,如果列表中存在 *,则允许所有请求源,默认值是 []
*/
config.AllowOrigins = origins
} else {
/*
(2) 允许全部origin
AllowOriginFunc: 接收参数 origin,函数体中的验证逻辑返回是否允许跨域请求。该配置项优先级高于 AllowOrigins []string,如果设置该配置项,AllowOrigins []string 配置项的设置被忽略
*/
config.AllowOriginFunc = func(origin string) bool {
return true
}
}
return cors.New(config)
}