Skip to content

Commit

Permalink
Added availability to set 200/204 for OPTIONS response status code
Browse files Browse the repository at this point in the history
  • Loading branch information
Dmytro Kishchenko committed Nov 10, 2023
1 parent ee4df80 commit d9d3b88
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 15 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@ _testmain.go
*.prof

coverage.out

.idea
36 changes: 21 additions & 15 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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,
}
}

Expand All @@ -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)
}
Expand Down
3 changes: 3 additions & 0 deletions cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit d9d3b88

Please sign in to comment.