Documentation ¶
Overview ¶
Package cors provides a middleware for Cross-origin resource sharing (CORS).
Cors describes the CrossOriginResourceSharing which is used to create a Container Filter that implements CORS. Cross-origin resource sharing (CORS) is a mechanism that allows JavaScript on a web page to make XMLHttpRequests to another domain, not the domain the JavaScript originated from.
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing http://enable-cors.org/server.html http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request
Index ¶
- type Option
- func OptionsError(err error) []Option
- func WithDebugLog(w io.Writer) Option
- func WithDefaultConfig(h scope.TypeID) Option
- func WithDisable(isDisabled bool, scopeIDs ...scope.TypeID) Option
- func WithErrorHandler(eh mw.ErrorHandler, scopeIDs ...scope.TypeID) Option
- func WithLogger(l log.Logger) Option
- func WithMarkPartiallyApplied(partially bool, scopeIDs ...scope.TypeID) Option
- func WithOptionFactory(f OptionFactoryFunc) Option
- func WithRootConfig(cg config.Getter) Option
- func WithServiceErrorHandler(eh mw.ErrorHandler) Option
- func WithSettings(stng Settings, scopeIDs ...scope.TypeID) Option
- type OptionFactories
- type OptionFactoryFunc
- type ScopedConfig
- type Service
- func (s *Service) ClearCache() error
- func (s *Service) ConfigByScope(websiteID, storeID int64) (ScopedConfig, error)
- func (s *Service) ConfigByScopeID(current scope.TypeID, parent scope.TypeID) (scpCfg ScopedConfig, _ error)
- func (s *Service) ConfigByScopedGetter(scpGet config.Scoped) (ScopedConfig, error)
- func (s *Service) DebugCache(w io.Writer) error
- func (s *Service) Options(opts ...Option) error
- func (s *Service) WithCORS(next http.Handler) http.Handler
- type Settings
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Option ¶
Option can be used as an argument in NewService to configure it with different settings.
func OptionsError ¶
OptionsError helper function to be used within the backend package or other sub-packages whose functions may return an OptionFactoryFunc.
func WithDebugLog ¶
WithDebugLog creates a new standard library based logger with debug mode enabled. The passed writer must be thread safe.
func WithDefaultConfig ¶
WithDefaultConfig applies the default CORS configuration settings based for a specific scope. This function overwrites any previous set options. Default values are:
- Allowed Methods: GET, POST
- Allowed Headers: Origin, Accept, Content-Type
func WithDisable ¶
WithDisable disables the current service and calls the next HTTP handler.
The variadic "scopeIDs" argument define to which scope the value gets applied and from which parent scope should be inherited. Setting no "scopeIDs" sets the value to the default scope. Setting one scope.TypeID defines the primary scope to which the value will be applied. Subsequent scope.TypeID are defining the fall back parent scopes to inherit the default or previously applied configuration from.
func WithErrorHandler ¶
func WithErrorHandler(eh mw.ErrorHandler, scopeIDs ...scope.TypeID) Option
WithErrorHandler adds a custom error handler. Gets called in the http.Handler after the scope can be extracted from the context.Context and the configuration has been found and is valid. The default error handler prints the error to the user and returns a http.StatusServiceUnavailable.
The variadic "scopeIDs" argument define to which scope the value gets applied and from which parent scope should be inherited. Setting no "scopeIDs" sets the value to the default scope. Setting one scope.TypeID defines the primary scope to which the value will be applied. Subsequent scope.TypeID are defining the fall back parent scopes to inherit the default or previously applied configuration from.
func WithLogger ¶
WithLogger convenient helper function to apply a logger to the Service type.
func WithMarkPartiallyApplied ¶
WithMarkPartiallyApplied if set to true marks a configuration for a scope as partially applied with functional options set via source code. The internal service knows that it must trigger additionally the OptionFactoryFunc to load configuration from a backend. Useful in the case where parts of the configurations are coming from backend storages and other parts like http handler have been set via code. This function should only be applied in case you work with WithOptionFactory().
The variadic "scopeIDs" argument define to which scope the value gets applied and from which parent scope should be inherited. Setting no "scopeIDs" sets the value to the default scope. Setting one scope.TypeID defines the primary scope to which the value will be applied. Subsequent scope.TypeID are defining the fall back parent scopes to inherit the default or previously applied configuration from.
func WithOptionFactory ¶
func WithOptionFactory(f OptionFactoryFunc) Option
WithOptionFactory applies a function which lazily loads the options from a slow backend (config.Getter) depending on the incoming scope within a request. For example applies the backend configuration to the service.
Once this option function has been set all other manually set option functions, which accept a scope and a scope ID as an argument, will NOT be overwritten by the new values retrieved from the configuration service.
cfgStruct, err := backendcors.NewConfigStructure() if err != nil { panic(err) } be := backendcors.New(cfgStruct) srv := cors.MustNewService( cors.WithOptionFactory(be.PrepareOptions()), )
func WithRootConfig ¶
WithRootConfig sets the root configuration service to retrieve the scoped base configuration. If you set the option WithOptionFactory() then the option WithRootConfig() does not need to be set as it won't get used.
func WithServiceErrorHandler ¶
func WithServiceErrorHandler(eh mw.ErrorHandler) Option
WithServiceErrorHandler sets the error handler on the Service object. Convenient helper function.
type OptionFactories ¶
type OptionFactories struct {
// contains filtered or unexported fields
}
OptionFactories allows to register multiple OptionFactoryFunc identified by their names. Those OptionFactoryFuncs will be loaded in the backend package depending on the configured name under a certain path. This type is embedded in the backendcors.Configuration type.
func NewOptionFactories ¶
func NewOptionFactories() *OptionFactories
NewOptionFactories creates a new struct and initializes the internal map for the registration of different option factories.
func (*OptionFactories) Deregister ¶
func (of *OptionFactories) Deregister(name string)
Deregister removes a functional option factory from the internal register.
func (*OptionFactories) Lookup ¶
func (of *OptionFactories) Lookup(name string) (OptionFactoryFunc, error)
Lookup returns a functional option factory identified by name or an error if the entry doesn't exists. May return a NotFound error behaviour.
func (*OptionFactories) Names ¶
func (of *OptionFactories) Names() []string
Names returns an unordered list of names of all registered functional option factories.
func (*OptionFactories) Register ¶
func (of *OptionFactories) Register(name string, factory OptionFactoryFunc)
Register adds another functional option factory to the internal register. Overwrites existing entries.
type OptionFactoryFunc ¶
OptionFactoryFunc a closure around a scoped configuration to figure out which options should be returned depending on the scope brought to you during a request.
type ScopedConfig ¶
type ScopedConfig struct { // Settings general CORS settings Settings // contains filtered or unexported fields }
ScopedConfig scoped based configuration and should not be embedded into your own types. Call ScopedConfig.ScopeID to know to which scope this configuration has been bound to.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service describes the CrossOriginResourceSharing which is used to create a Container Filter that implements CORS. Cross-origin resource sharing (CORS) is a mechanism that allows JavaScript on a web page to make XMLHttpRequests to another domain, not the domain the JavaScript originated from.
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing http://enable-cors.org/server.html http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request
func (*Service) ClearCache ¶
ClearCache clears the internal map storing all scoped configurations. You must reapply all functional options. TODO(CyS) all previously applied options will be automatically reapplied.
func (*Service) ConfigByScope ¶
func (s *Service) ConfigByScope(websiteID, storeID int64) (ScopedConfig, error)
ConfigByScope creates a new scoped configuration depending on the Service.useWebsite flag. If useWebsite==true the scoped configuration contains only the website->default scope despite setting a store scope. If an OptionFactory is set the configuration gets loaded from the backend. A nil root config causes a panic.
func (*Service) ConfigByScopeID ¶
func (s *Service) ConfigByScopeID(current scope.TypeID, parent scope.TypeID) (scpCfg ScopedConfig, _ error)
ConfigByScopeID returns the correct configuration for a scope and may fall back to the next higher scope: store -> website -> default. If `current` TypeID is Store, then the `parent` can only be Website or Default. If an entry for a scope cannot be found the next higher scope gets looked up and the pointer of the next higher scope gets assigned to the current scope. This prevents redundant configurations and enables us to change one scope configuration with an impact on all other scopes which depend on the parent scope. A zero `parent` triggers no further look ups. This function does not load any configuration (config.Getter related) from the backend and accesses the internal map of the Service directly.
Important: a "current" scope cannot have multiple "parent" scopes.
func (*Service) ConfigByScopedGetter ¶
func (s *Service) ConfigByScopedGetter(scpGet config.Scoped) (ScopedConfig, error)
ConfigByScopedGetter returns the internal configuration depending on the ScopedGetter. Mainly used within the middleware. If you have applied the option WithOptionFactory() the configuration will be pulled out only one time from the backend configuration service. The field optionInflight handles the guaranteed atomic single loading for each scope.
func (*Service) DebugCache ¶
DebugCache uses Sprintf to write an ordered list (by scope.TypeID) into a writer. Only usable for debugging.
type Settings ¶
type Settings struct { // AllowedOrigins is a list of origins a cross-domain request can be // executed from. If the special "*" value is present in the list, all // origins will be allowed. An origin may contain a wildcard (*) to replace // 0 or more characters (i.e.: http://*.domain.com). Usage of wildcards // implies a small performance penality. Only one wildcard can be used per // origin. Default value is ["*"]. Normalized list of plain allowed origins. AllowedOrigins []string // AllowedHeaders normalized list of allowed headers the client is allowed // to use with cross-domain requests. If the special "*" value is present in // the list, all headers will be allowed. Default value is [] but "Origin" // is always appended to the list. AllowedHeaders []string // AllowedMethods normalized list of methods, the client is allowed to use // with cross-domain requests. Default value is simple methods (GET and // POST) AllowedMethods []string // ExposedHeaders indicates which headers are safe to expose to the API of a // CORS API specification. Normalized list of exposed headers. ExposedHeaders []string // MaxAge in seconds will be added to the header, if set. Indicates how long // (in seconds) the results of a preflight request can be cached. MaxAge string // AllowOriginFunc is a custom function to validate the origin. It take the // origin as argument and returns true if allowed or false otherwise. If // this option is set, the content of AllowedOrigins is ignored. AllowOriginFunc func(origin string) bool // AllowedOriginsAll set to true when allowed origins contains a "*" AllowedOriginsAll bool // AllowedHeadersAll set to true when allowed headers contains a "*" AllowedHeadersAll bool // AllowCredentials indicates whether the request can include user // credentials like cookies, HTTP authentication or client side SSL // certificates. AllowCredentials bool // OptionsPassthrough instructs preflight to let other potential next // handlers to process the OPTIONS method. Turn this on if your application // handles OPTIONS. OptionsPassthrough bool // contains filtered or unexported fields }
Settings general settings for the cors service. Those settings will be applied via functional options on a per scope basis.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package backendcors defines the backend configuration options and element slices.
|
Package backendcors defines the backend configuration options and element slices. |