Skip to content

Commit

Permalink
[#64]: feature: supports regex for origin
Browse files Browse the repository at this point in the history
  • Loading branch information
rustatian authored Nov 4, 2023
2 parents e22a7c2 + 2323e5c commit 496ef42
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
3 changes: 2 additions & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ type Config struct {
// CORSConfig headers configuration.
type CORSConfig struct {
// AllowedOrigin: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
AllowedOrigin string `mapstructure:"allowed_origin"`
AllowedOrigin string `mapstructure:"allowed_origin"`
AllowedOriginRegex string `mapstructure:"allowed_origin_regex"`
// AllowedHeaders: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
AllowedHeaders string `mapstructure:"allowed_headers"`
// AllowedMethods: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
Expand Down
20 changes: 17 additions & 3 deletions plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package headers
import (
"fmt"
"net/http"
"regexp"
"strings"

"github.com/roadrunner-server/errors"
Expand Down Expand Up @@ -31,9 +32,10 @@ type Configurer interface {
// Plugin serves headers files. Potentially convert into middleware?
type Plugin struct {
// server configuration (location, forbidden files and etc)
cfg *Config
prop propagation.TextMapPropagator
cors *cors.Cors
cfg *Config
prop propagation.TextMapPropagator
cors *cors.Cors
allowedOriginRegex *regexp.Regexp
}

// Init must return configure service and return true if service hasStatus enabled. Must return error in case of
Expand Down Expand Up @@ -70,6 +72,18 @@ func (p *Plugin) Init(cfg Configurer) error {
opts.AllowedOrigins = strings.Split(p.cfg.CORS.AllowedOrigin, ",")
}

// if this option is set, the content of `AllowedOrigins` is ignored
if p.cfg.CORS.AllowedOriginRegex != "" {
var err error
p.allowedOriginRegex, err = regexp.Compile(p.cfg.CORS.AllowedOriginRegex)
if err != nil {
return errors.E(op, err)
}
opts.AllowOriginFunc = func(origin string) bool {
return p.allowedOriginRegex.MatchString(origin)
}
}

if p.cfg.CORS.AllowedMethods != "" {
// trim all spaces
p.cfg.CORS.AllowedMethods = strings.Trim(p.cfg.CORS.AllowedMethods, " ")
Expand Down

0 comments on commit 496ef42

Please sign in to comment.