config

package
v1.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 6, 2020 License: Apache-2.0 Imports: 12 Imported by: 4

Documentation

Overview

Package config defines the config structs and some config parser interfaces and implementations

Index

Constants

View Source
const (
	// BracketsRouterPatternBuilder uses brackets as route params delimiter
	BracketsRouterPatternBuilder = iota
	// ColonRouterPatternBuilder use a colon as route param delimiter
	ColonRouterPatternBuilder
	// DefaultMaxIdleConnsPerHost is the default value for the MaxIdleConnsPerHost param
	DefaultMaxIdleConnsPerHost = 250
	// DefaultTimeout is the default value to use for the ServiceConfig.Timeout param
	DefaultTimeout = 2 * time.Second

	// ConfigVersion is the current version of the config struct
	ConfigVersion = 2
)

Variables

View Source
var ConfigGetters = map[string]ConfigGetter{/* contains filtered or unexported fields */}

ConfigGetters map than match namespaces and ConfigGetter so the components knows which type to expect returned by the ConfigGetter ie: if we look for the defaultNamespace in the map, we will get the DefaultConfigGetter implementation which will return a ExtraConfig when called

View Source
var RoutingPattern = ColonRouterPatternBuilder

RoutingPattern to use during route conversion. By default, use the colon router pattern

Functions

func CheckErr added in v1.1.3

func CheckErr(err error, configFile string) error

CheckErr returns a proper documented error

func DefaultConfigGetter

func DefaultConfigGetter(extra ExtraConfig) interface{}

DefaultConfigGetter is the Default implementation for ConfigGetter, it just returns the ExtraConfig map.

Types

type Backend

type Backend struct {
	// Group defines the name of the property the response should be moved to. If empty, the response is
	// not changed
	Group string `mapstructure:"group"`
	// Method defines the HTTP method of the request to send to the backend
	Method string `mapstructure:"method"`
	// Host is a set of hosts of the API
	Host []string `mapstructure:"host"`
	// HostSanitizationDisabled can be set to false if the hostname should be sanitized
	HostSanitizationDisabled bool `mapstructure:"disable_host_sanitize"`
	// URLPattern is the URL pattern to use to locate the resource to be consumed
	URLPattern string `mapstructure:"url_pattern"`
	// Deprecated: use DenyList
	// Blacklist is a set of response fields to remove. If empty, the filter id not used
	Blacklist []string `mapstructure:"blacklist"`
	// Deprecated: use AllowList
	// Whitelist is a set of response fields to allow. If empty, the filter id not used
	Whitelist []string `mapstructure:"whitelist"`
	// AllowList is a set of response fields to remove. If empty, the filter id not used
	AllowList []string `mapstructure:"deny"`
	// DenyList is a set of response fields to allow. If empty, the filter id not used
	DenyList []string `mapstructure:"allow"`
	// map of response fields to be renamed and their new names
	Mapping map[string]string `mapstructure:"mapping"`
	// the encoding format
	Encoding string `mapstructure:"encoding"`
	// the response to process is a collection
	IsCollection bool `mapstructure:"is_collection"`
	// name of the field to extract to the root. If empty, the formater will do nothing
	Target string `mapstructure:"target"`
	// name of the service discovery driver to use
	SD string `mapstructure:"sd"`

	// list of keys to be replaced in the URLPattern
	URLKeys []string
	// number of concurrent calls this endpoint must send to the API
	ConcurrentCalls int
	// timeout of this backend
	Timeout time.Duration
	// decoder to use in order to parse the received response from the API
	Decoder encoding.Decoder `json:"-"`
	// Backend Extra configuration for customized behaviours
	ExtraConfig ExtraConfig `mapstructure:"extra_config"`
}

Backend defines how krakend should connect to the backend service (the API resource to consume) and how it should process the received response

type ConfigGetter

type ConfigGetter func(ExtraConfig) interface{}

ConfigGetter is a function for parsing ExtraConfig into a previously know type

type EndpointConfig

type EndpointConfig struct {
	// url pattern to be registered and exposed to the world
	Endpoint string `mapstructure:"endpoint"`
	// HTTP method of the endpoint (GET, POST, PUT, etc)
	Method string `mapstructure:"method"`
	// set of definitions of the backends to be linked to this endpoint
	Backend []*Backend `mapstructure:"backend"`
	// number of concurrent calls this endpoint must send to the backends
	ConcurrentCalls int `mapstructure:"concurrent_calls"`
	// timeout of this endpoint
	Timeout time.Duration `mapstructure:"timeout"`
	// duration of the cache header
	CacheTTL time.Duration `mapstructure:"cache_ttl"`
	// list of query string params to be extracted from the URI
	QueryString []string `mapstructure:"querystring_params"`
	// Endpoint Extra configuration for customized behaviour
	ExtraConfig ExtraConfig `mapstructure:"extra_config"`
	// HeadersToPass defines the list of headers to pass to the backends
	HeadersToPass []string `mapstructure:"headers_to_pass"`
	// OutputEncoding defines the encoding strategy to use for the endpoint responses
	OutputEncoding string `mapstructure:"output_encoding"`
}

EndpointConfig defines the configuration of a single endpoint to be exposed by the krakend service

type EndpointMatchError added in v1.1.3

type EndpointMatchError struct {
	Path   string
	Method string
	Err    error
}

EndpointMatchError is the error returned by the configuration init process when the endpoint pattern check fails

func (*EndpointMatchError) Error added in v1.1.3

func (e *EndpointMatchError) Error() string

Error returns a string representation of the EndpointMatchError

type EndpointPathError added in v1.1.3

type EndpointPathError struct {
	Path   string
	Method string
}

EndpointPathError is the error returned by the configuration init process when an endpoint is using a forbidden path

func (*EndpointPathError) Error added in v1.1.3

func (e *EndpointPathError) Error() string

Error returns a string representation of the EndpointPathError

type ExtraConfig

type ExtraConfig map[string]interface{}

ExtraConfig is a type to store extra configurations for customized behaviours

type FileReaderFunc

type FileReaderFunc func(string) ([]byte, error)

FileReaderFunc is a function used to read the content of a config file

type NoBackendsError added in v1.1.3

type NoBackendsError struct {
	Path   string
	Method string
}

NoBackendsError is the error returned by the configuration init process when an endpoint is connected to 0 backends

func (*NoBackendsError) Error added in v1.1.3

func (n *NoBackendsError) Error() string

Error returns a string representation of the NoBackendsError

type ParseError added in v1.1.3

type ParseError struct {
	ConfigFile string
	Offset     int
	Row        int
	Col        int
	Err        error
}

ParseError is an error containing details regarding the row and column where an parse error occurred

func NewParseError added in v1.1.3

func NewParseError(err error, configFile string, offset int) *ParseError

NewParseError returns a new ParseError

func (*ParseError) Error added in v1.1.3

func (p *ParseError) Error() string

Error returns the error message for the ParseError

type Parser

type Parser interface {
	Parse(configFile string) (ServiceConfig, error)
}

Parser reads a configuration file, parses it and returns the content as an init ServiceConfig struct

func NewParser

func NewParser() Parser

NewParser creates a new parser using the json library

func NewParserWithFileReader

func NewParserWithFileReader(f FileReaderFunc) Parser

NewParserWithFileReader returns a Parser with the injected FileReaderFunc function

type ParserFunc

type ParserFunc func(string) (ServiceConfig, error)

ParserFunc type is an adapter to allow the use of ordinary functions as subscribers. If f is a function with the appropriate signature, ParserFunc(f) is a Parser that calls f.

func (ParserFunc) Parse

func (f ParserFunc) Parse(configFile string) (ServiceConfig, error)

Parse implements the Parser interface

type Plugin

type Plugin struct {
	Folder  string `mapstructure:"folder"`
	Pattern string `mapstructure:"pattern"`
}

Plugin contains the config required by the plugin module

type ServiceConfig

type ServiceConfig struct {
	// name of the service
	Name string `mapstructure:"name"`
	// set of endpoint definitions
	Endpoints []*EndpointConfig `mapstructure:"endpoints"`
	// defafult timeout
	Timeout time.Duration `mapstructure:"timeout"`
	// default TTL for GET
	CacheTTL time.Duration `mapstructure:"cache_ttl"`
	// default set of hosts
	Host []string `mapstructure:"host"`
	// port to bind the krakend service
	Port int `mapstructure:"port"`
	// version code of the configuration
	Version int `mapstructure:"version"`
	// OutputEncoding defines the default encoding strategy to use for the endpoint responses
	OutputEncoding string `mapstructure:"output_encoding"`
	// Extra configuration for customized behaviour
	ExtraConfig ExtraConfig `mapstructure:"extra_config"`

	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body.
	//
	// Because ReadTimeout does not let Handlers make per-request
	// decisions on each request body's acceptable deadline or
	// upload rate, most users will prefer to use
	// ReadHeaderTimeout. It is valid to use them both.
	ReadTimeout time.Duration `mapstructure:"read_timeout"`
	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset whenever a new
	// request's header is read. Like ReadTimeout, it does not
	// let Handlers make decisions on a per-request basis.
	WriteTimeout time.Duration `mapstructure:"write_timeout"`
	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alives are enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, ReadHeaderTimeout is used.
	IdleTimeout time.Duration `mapstructure:"idle_timeout"`
	// ReadHeaderTimeout is the amount of time allowed to read
	// request headers. The connection's read deadline is reset
	// after reading the headers and the Handler can decide what
	// is considered too slow for the body.
	ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout"`

	// DisableKeepAlives, if true, prevents re-use of TCP connections
	// between different HTTP requests.
	DisableKeepAlives bool `mapstructure:"disable_keep_alives"`
	// DisableCompression, if true, prevents the Transport from
	// requesting compression with an "Accept-Encoding: gzip"
	// request header when the Request contains no existing
	// Accept-Encoding value. If the Transport requests gzip on
	// its own and gets a gzipped response, it's transparently
	// decoded in the Response.Body. However, if the user
	// explicitly requested gzip it is not automatically
	// uncompressed.
	DisableCompression bool `mapstructure:"disable_compression"`
	// MaxIdleConns controls the maximum number of idle (keep-alive)
	// connections across all hosts. Zero means no limit.
	MaxIdleConns int `mapstructure:"max_idle_connections"`
	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
	// (keep-alive) connections to keep per-host. If zero,
	// DefaultMaxIdleConnsPerHost is used.
	MaxIdleConnsPerHost int `mapstructure:"max_idle_connections_per_host"`
	// IdleConnTimeout is the maximum amount of time an idle
	// (keep-alive) connection will remain idle before closing
	// itself.
	// Zero means no limit.
	IdleConnTimeout time.Duration `mapstructure:"idle_connection_timeout"`
	// ResponseHeaderTimeout, if non-zero, specifies the amount of
	// time to wait for a server's response headers after fully
	// writing the request (including its body, if any). This
	// time does not include the time to read the response body.
	ResponseHeaderTimeout time.Duration `mapstructure:"response_header_timeout"`
	// ExpectContinueTimeout, if non-zero, specifies the amount of
	// time to wait for a server's first response headers after fully
	// writing the request headers if the request has an
	// "Expect: 100-continue" header. Zero means no timeout and
	// causes the body to be sent immediately, without
	// waiting for the server to approve.
	// This time does not include the time to send the request header.
	ExpectContinueTimeout time.Duration `mapstructure:"expect_continue_timeout"`
	// DialerTimeout is the maximum amount of time a dial will wait for
	// a connect to complete. If Deadline is also set, it may fail
	// earlier.
	//
	// The default is no timeout.
	//
	// When using TCP and dialing a host name with multiple IP
	// addresses, the timeout may be divided between them.
	//
	// With or without a timeout, the operating system may impose
	// its own earlier timeout. For instance, TCP timeouts are
	// often around 3 minutes.
	DialerTimeout time.Duration `mapstructure:"dialer_timeout"`
	// DialerFallbackDelay specifies the length of time to wait before
	// spawning a fallback connection, when DualStack is enabled.
	// If zero, a default delay of 300ms is used.
	DialerFallbackDelay time.Duration `mapstructure:"dialer_fallback_delay"`
	// DialerKeepAlive specifies the keep-alive period for an active
	// network connection.
	// If zero, keep-alives are not enabled. Network protocols
	// that do not support keep-alives ignore this field.
	DialerKeepAlive time.Duration `mapstructure:"dialer_keep_alive"`

	// DisableStrictREST flags if the REST enforcement is disabled
	DisableStrictREST bool `mapstructure:"disable_rest"`

	// Plugin defines the configuration for the plugin loader
	Plugin *Plugin `mapstructure:"plugin"`

	// TLS defines the configuration params for enabling TLS (HTTPS & HTTP/2) at
	// the router layer
	TLS *TLS `mapstructure:"tls"`

	// run krakend in debug mode
	Debug bool
	// contains filtered or unexported fields
}

ServiceConfig defines the krakend service

func (*ServiceConfig) Hash

func (s *ServiceConfig) Hash() (string, error)

Hash returns the sha 256 hash of the configuration in a standard base64 encoded string

func (*ServiceConfig) Init

func (s *ServiceConfig) Init() error

Init initializes the configuration struct and its defined endpoints and backends. Init also sanitizes the values, applies the default ones whenever necessary and normalizes all the things.

type TLS

type TLS struct {
	IsDisabled               bool     `mapstructure:"disabled"`
	PublicKey                string   `mapstructure:"public_key"`
	PrivateKey               string   `mapstructure:"private_key"`
	MinVersion               string   `mapstructure:"min_version"`
	MaxVersion               string   `mapstructure:"max_version"`
	CurvePreferences         []uint16 `mapstructure:"curve_preferences"`
	PreferServerCipherSuites bool     `mapstructure:"prefer_server_cipher_suites"`
	CipherSuites             []uint16 `mapstructure:"cipher_suites"`
}

TLS defines the configuration params for enabling TLS (HTTPS & HTTP/2) at the router layer

type URI

type URI int

URI implements the URIParser interface

func (URI) CleanHost

func (URI) CleanHost(host string) string

CleanHost sanitizes the received host

func (URI) CleanHosts

func (u URI) CleanHosts(hosts []string) []string

CleanHosts applies the CleanHost method to every member of the received array of hosts

func (URI) CleanPath

func (URI) CleanPath(path string) string

CleanPath trims all the extra slashes from the received URI path

func (URI) GetEndpointPath

func (u URI) GetEndpointPath(path string, params []string) string

GetEndpointPath applies the proper replacement in the received path to generate valid route patterns

type URIParser

type URIParser interface {
	CleanHosts([]string) []string
	CleanHost(string) string
	CleanPath(string) string
	GetEndpointPath(string, []string) string
}

URIParser defines the interface for all the URI manipulation required by KrakenD

func NewURIParser

func NewURIParser() URIParser

NewURIParser creates a new URIParser using the package variable RoutingPattern

type UndefinedOutputParamError added in v1.1.3

type UndefinedOutputParamError struct {
	Endpoint     string
	Method       string
	Backend      int
	InputParams  []string
	OutputParams []string
	Param        string
}

UndefinedOutputParamError is the error returned by the configuration init process when an output param is not present in the input param set

func (*UndefinedOutputParamError) Error added in v1.1.3

func (u *UndefinedOutputParamError) Error() string

Error returns a string representation of the UndefinedOutputParamError

type UnsupportedVersionError added in v1.1.3

type UnsupportedVersionError struct {
	Have int
	Want int
}

UnsupportedVersionError is the error returned by the configuration init process when the configuration version is not supoprted

func (*UnsupportedVersionError) Error added in v1.1.3

func (u *UnsupportedVersionError) Error() string

Error returns a string representation of the UnsupportedVersionError

type WrongNumberOfParamsError added in v1.1.3

type WrongNumberOfParamsError struct {
	Endpoint     string
	Method       string
	Backend      int
	InputParams  []string
	OutputParams []string
}

WrongNumberOfParamsError is the error returned by the configuration init process when the number of output params is greatter than the number of input params

func (*WrongNumberOfParamsError) Error added in v1.1.3

func (w *WrongNumberOfParamsError) Error() string

Error returns a string representation of the WrongNumberOfParamsError

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL