-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcors.go
171 lines (146 loc) · 5.44 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/*
This is a cors middleware for the gin http framwork and can be used to configure the cors behaviour of your application
*/
package cors
import (
"fmt"
"net/http"
"slices"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
/*
Defines the configuration of your cors middleware
*/
type Config struct {
// All the allowed origins in an array. The default is "*"
// The default cannot be used when AllowCredentials is true
// [MDN Web Docs]
//
// [MDN Web Docs]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
AllowedOrigins []string
// All the allowed HTTP Methodes. The default is "*"
// The default cannot be used when AllowCredentials is true
// [MDN Web Docs]
//
// [MDN Web Docs]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
AllowedMethods []string
// All the allowed Headers that can be sent from the client. The default is "*"
// The default cannot be used when AllowCredentials is true
// Note that the Authorization header cannot be wildcarded and needs to be listed explicitly [MDN Web Docs]
//
// [MDN Web Docs]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
AllowedHeaders []string
// The headers which should be readable by the client. The default is "*"
// The default cannot be used when AllowCredentials is true
// [MDN Web Docs]
//
// [MDN Web Docs]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
ExposeHeaders []string
// If you allow receiving cookies and Authorization headers. The default is false
// [MDN Web Docs]
//
// [MDN Web Docs]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
AllowCredentials bool
// The maximum age of your preflight requests. The default is 1 day
// [MDN Web Docs]
//
// [MDN Web Docs]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
MaxAge time.Duration
}
/*
Adds wildcard to the array if no value was set.
Panics if the allowCredentials is true and the header is a wildcard
*/
func checkCredentials(header []string, allowCredentials bool, headerName string) []string {
if header == nil || len(header) <= 0 {
if allowCredentials {
panic(fmt.Sprintf("The %s must be set when AllowCredentials is true", headerName))
}
return []string{"*"}
}
if slices.Contains(header, "*") && allowCredentials {
panic(fmt.Sprintf("The %s cannot contain the \"*\" wildcard when AllowCredentials is true", headerName))
}
return header
}
/*
Validates the config and sets empty values to their defaults if necessary
*/
func (c Config) validate() Config {
c.AllowedOrigins = checkCredentials(c.AllowedOrigins, c.AllowCredentials, "allowed origins")
c.AllowedMethods = checkCredentials(c.AllowedMethods, c.AllowCredentials, "allowed methods")
c.AllowedHeaders = checkCredentials(c.AllowedHeaders, c.AllowCredentials, "allowed headers")
c.ExposeHeaders = checkCredentials(c.ExposeHeaders, c.AllowCredentials, "expose headers")
for i, method := range c.AllowedMethods {
c.AllowedMethods[i] = strings.ToUpper(method)
}
c.AllowedMethods = slices.Compact(c.AllowedMethods)
if c.MaxAge == 0 {
c.MaxAge = 24 * time.Hour
}
return c
}
/*
The default config for the cors middleware
Config{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"*"},
AllowedHeaders: []string{"Authorization", "Conten-Type", "Content-Length"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: false,
MaxAge: 24 * time.Hour,
}
*/
func DefaultConfig() Config {
return Config{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"*"},
AllowedHeaders: []string{"Content-Type", "Content-Length"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: false,
MaxAge: 24 * time.Hour,
}
}
/*
CORS Middleware for Gin which handles CORS headers and preflight requests
needs a cors config
*/
func CorsMiddleware(config Config) gin.HandlerFunc {
config = config.validate()
return func(c *gin.Context) {
currentOrigin := c.Request.Header.Get("Origin")
c.Writer.Header().Set("Vary", "Origin")
if currentOrigin == "" {
c.AbortWithStatus(http.StatusForbidden)
}
if !slices.Contains(config.AllowedOrigins, "*") && !slices.Contains(config.AllowedOrigins, currentOrigin) {
c.AbortWithStatus(http.StatusForbidden)
}
var method = strings.ToUpper(c.Request.Method)
if !slices.Contains(config.AllowedMethods, "*") && !slices.Contains(config.AllowedMethods, method) && method != "OPTIONS" {
c.AbortWithStatus(http.StatusMethodNotAllowed)
}
if slices.Contains(config.AllowedOrigins, "*") {
currentOrigin = "*"
}
var preflight = method == "OPTIONS"
if preflight {
// Headers for preflight requests
c.Writer.Header().Set("Access-Control-Allow-Methods", strings.Join(config.AllowedMethods, ", "))
c.Writer.Header().Set("Access-Control-Allow-Headers", strings.Join(config.AllowedHeaders, ", "))
c.Writer.Header().Set("Access-Control-Max-Age", strconv.FormatInt(int64(config.MaxAge.Seconds()), 10))
}
// Headers for all requests
c.Writer.Header().Set("Access-Control-Allow-Origin", currentOrigin)
c.Writer.Header().Set("Access-Control-Allow-Credentials", strconv.FormatBool(config.AllowCredentials))
c.Writer.Header().Set("Access-Control-Expose-Headers", strings.Join(config.ExposeHeaders, ", "))
if preflight {
// If this is a preflight request we don't need to continue
c.AbortWithStatus(204)
}
c.Next()
}
}