From d9d3b88580f53a2816ce06fd2d39541a531807f2 Mon Sep 17 00:00:00 2001 From: Dmytro Kishchenko Date: Fri, 10 Nov 2023 14:00:00 +0100 Subject: [PATCH] Added availability to set 200/204 for OPTIONS response status code --- .gitignore | 2 ++ config.go | 36 +++++++++++++++++++++--------------- cors.go | 3 +++ 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index b4ecae3..002df84 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,5 @@ _testmain.go *.prof coverage.out + +.idea diff --git a/config.go b/config.go index 735c8c1..427cfc0 100644 --- a/config.go +++ b/config.go @@ -8,13 +8,14 @@ import ( ) type cors struct { - allowAllOrigins bool - allowCredentials bool - allowOriginFunc func(string) bool - allowOrigins []string - normalHeaders http.Header - preflightHeaders http.Header - wildcardOrigins [][]string + allowAllOrigins bool + allowCredentials bool + allowOriginFunc func(string) bool + allowOrigins []string + normalHeaders http.Header + preflightHeaders http.Header + wildcardOrigins [][]string + optionsResponseStatusCode int } var ( @@ -48,14 +49,19 @@ func newCors(config Config) *cors { } } + if config.OptionsResponseStatusCode == 0 { + config.OptionsResponseStatusCode = http.StatusNoContent + } + return &cors{ - allowOriginFunc: config.AllowOriginFunc, - allowAllOrigins: config.AllowAllOrigins, - allowCredentials: config.AllowCredentials, - allowOrigins: normalize(config.AllowOrigins), - normalHeaders: generateNormalHeaders(config), - preflightHeaders: generatePreflightHeaders(config), - wildcardOrigins: config.parseWildcardRules(), + allowOriginFunc: config.AllowOriginFunc, + allowAllOrigins: config.AllowAllOrigins, + allowCredentials: config.AllowCredentials, + allowOrigins: normalize(config.AllowOrigins), + normalHeaders: generateNormalHeaders(config), + preflightHeaders: generatePreflightHeaders(config), + wildcardOrigins: config.parseWildcardRules(), + optionsResponseStatusCode: config.OptionsResponseStatusCode, } } @@ -80,7 +86,7 @@ func (cors *cors) applyCors(c *gin.Context) { if c.Request.Method == "OPTIONS" { cors.handlePreflight(c) - defer c.AbortWithStatus(http.StatusNoContent) // Using 204 is better than 200 when the request status is OPTIONS + defer c.AbortWithStatus(cors.optionsResponseStatusCode) } else { cors.handleNormal(c) } diff --git a/cors.go b/cors.go index 4113437..f3ab41e 100644 --- a/cors.go +++ b/cors.go @@ -53,6 +53,9 @@ type Config struct { // Allows usage of file:// schema (dangerous!) use it only when you 100% sure it's needed AllowFiles bool + + // Allows to pass custom OPTIONS response status code for old browsers / clients + OptionsResponseStatusCode int } // AddAllowMethods is allowed to add custom methods