github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/plugin/cors/setup.go (about)

     1  package cors
     2  
     3  import (
     4  	"github.com/asaskevich/govalidator"
     5  	"github.com/hellofresh/janus/pkg/plugin"
     6  	"github.com/hellofresh/janus/pkg/proxy"
     7  	"github.com/rs/cors"
     8  )
     9  
    10  // Config represents the CORS configuration
    11  type Config struct {
    12  	AllowedOrigins     []string `json:"domains"`
    13  	AllowedMethods     []string `json:"methods"`
    14  	AllowedHeaders     []string `json:"request_headers"`
    15  	ExposedHeaders     []string `json:"exposed_headers"`
    16  	OptionsPassthrough bool     `json:"options_passthrough"`
    17  }
    18  
    19  func init() {
    20  	plugin.RegisterPlugin("cors", plugin.Plugin{
    21  		Action:   setupCors,
    22  		Validate: validateConfig,
    23  	})
    24  }
    25  
    26  func setupCors(def *proxy.RouterDefinition, rawConfig plugin.Config) error {
    27  	var config Config
    28  
    29  	err := plugin.Decode(rawConfig, &config)
    30  	if err != nil {
    31  		return err
    32  	}
    33  
    34  	mw := cors.New(cors.Options{
    35  		AllowedOrigins:     config.AllowedOrigins,
    36  		AllowedMethods:     config.AllowedMethods,
    37  		AllowedHeaders:     config.AllowedHeaders,
    38  		ExposedHeaders:     config.ExposedHeaders,
    39  		OptionsPassthrough: config.OptionsPassthrough,
    40  		AllowCredentials:   true,
    41  	})
    42  
    43  	def.AddMiddleware(mw.Handler)
    44  	return nil
    45  }
    46  
    47  func validateConfig(rawConfig plugin.Config) (bool, error) {
    48  	var config Config
    49  	err := plugin.Decode(rawConfig, &config)
    50  	if err != nil {
    51  		return false, err
    52  	}
    53  
    54  	return govalidator.ValidateStruct(config)
    55  }