Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: supports regex for origin #64

Merged
merged 3 commits into from
Nov 4, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"`
AllowedOriginWildcard string `mapstructure:"allowed_origin_wildcard"`
cv65kr marked this conversation as resolved.
Show resolved Hide resolved
// 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.AllowedOriginWildcard != "" {
var err error
p.allowedOriginRegex, err = regexp.Compile(p.cfg.CORS.AllowedOriginWildcard)
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
Loading