Skip to content

Commit d3f0a2b

Browse files
committedSep 5, 2023
Allow 0 max-age
Fixes #152
1 parent 6599721 commit d3f0a2b

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed
 

‎cors.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,10 @@ type Options struct {
6666
// API specification
6767
ExposedHeaders []string
6868
// MaxAge indicates how long (in seconds) the results of a preflight request
69-
// can be cached
69+
// can be cached. Default value is 0, which stands for no
70+
// Access-Control-Max-Age header to be sent back, resulting in browsers
71+
// using their default value (5s by spec). If you need to force a 0 max-age,
72+
// set `MaxAge` to a negative value (ie: -1).
7073
MaxAge int
7174
// AllowCredentials indicates whether the request can include user credentials like
7275
// cookies, HTTP authentication or client side SSL certificates.
@@ -362,6 +365,8 @@ func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) {
362365
}
363366
if c.maxAge > 0 {
364367
headers.Set("Access-Control-Max-Age", strconv.Itoa(c.maxAge))
368+
} else if c.maxAge < 0 {
369+
headers.Set("Access-Control-Max-Age", "0")
365370
}
366371
c.logf(" Preflight response headers: %v", headers)
367372
}

‎cors_test.go

+20
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,26 @@ func TestSpec(t *testing.T) {
242242
},
243243
true,
244244
},
245+
{
246+
"MaxAgeNegative",
247+
Options{
248+
AllowedOrigins: []string{"http://example.com/"},
249+
AllowedMethods: []string{"GET"},
250+
MaxAge: -1,
251+
},
252+
"OPTIONS",
253+
map[string]string{
254+
"Origin": "http://example.com/",
255+
"Access-Control-Request-Method": "GET",
256+
},
257+
map[string]string{
258+
"Vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
259+
"Access-Control-Allow-Origin": "http://example.com/",
260+
"Access-Control-Allow-Methods": "GET",
261+
"Access-Control-Max-Age": "0",
262+
},
263+
true,
264+
},
245265
{
246266
"AllowedMethod",
247267
Options{

0 commit comments

Comments
 (0)
Please sign in to comment.