Skip to content

Commit

Permalink
chore(options): Added availability to set 200/204 for OPTIONS request…
Browse files Browse the repository at this point in the history
… status (#129)

Co-authored-by: Dmytro Kishchenko <d.kischenko@sweet.tv>
  • Loading branch information
dkischenko and Dmytro Kishchenko committed Nov 25, 2023
1 parent ee4df80 commit f8b2357
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 15 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Expand Up @@ -21,3 +21,5 @@ _testmain.go
*.prof

coverage.out

.idea
36 changes: 21 additions & 15 deletions config.go
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
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 f8b2357

Please sign in to comment.