From d3f0a2b9d89dc78f36ca65ffc4ff02f6391982d2 Mon Sep 17 00:00:00 2001 From: Olivier Poitrey Date: Tue, 5 Sep 2023 14:14:00 +0200 Subject: [PATCH] Allow 0 max-age Fixes #152 --- cors.go | 7 ++++++- cors_test.go | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/cors.go b/cors.go index 6d1affe..6e4e80a 100644 --- a/cors.go +++ b/cors.go @@ -66,7 +66,10 @@ type Options struct { // API specification ExposedHeaders []string // MaxAge indicates how long (in seconds) the results of a preflight request - // can be cached + // can be cached. Default value is 0, which stands for no + // Access-Control-Max-Age header to be sent back, resulting in browsers + // using their default value (5s by spec). If you need to force a 0 max-age, + // set `MaxAge` to a negative value (ie: -1). MaxAge int // AllowCredentials indicates whether the request can include user credentials like // cookies, HTTP authentication or client side SSL certificates. @@ -362,6 +365,8 @@ func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) { } if c.maxAge > 0 { headers.Set("Access-Control-Max-Age", strconv.Itoa(c.maxAge)) + } else if c.maxAge < 0 { + headers.Set("Access-Control-Max-Age", "0") } c.logf(" Preflight response headers: %v", headers) } diff --git a/cors_test.go b/cors_test.go index 3c05326..a46233c 100644 --- a/cors_test.go +++ b/cors_test.go @@ -242,6 +242,26 @@ func TestSpec(t *testing.T) { }, true, }, + { + "MaxAgeNegative", + Options{ + AllowedOrigins: []string{"http://example.com/"}, + AllowedMethods: []string{"GET"}, + MaxAge: -1, + }, + "OPTIONS", + map[string]string{ + "Origin": "http://example.com/", + "Access-Control-Request-Method": "GET", + }, + map[string]string{ + "Vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Headers", + "Access-Control-Allow-Origin": "http://example.com/", + "Access-Control-Allow-Methods": "GET", + "Access-Control-Max-Age": "0", + }, + true, + }, { "AllowedMethod", Options{