Documentation ¶
Overview ¶
Package service contains the logic to build a HTTP/Rest Service for the MiSSy runtime environment
Index ¶
- Constants
- func AuthHandler(h http.Handler) http.Handler
- func FinalHandler(pattern string) func(h http.Handler) http.Handler
- func IsRequestTokenValid(r *http.Request) bool
- func IsSignedTokenValid(signedToken string) bool
- func NewClient() *http.Client
- func RawToken(r *http.Request) (string, error)
- func StartTimerHandler(h http.Handler) http.Handler
- func Token(r *http.Request) *jwt.Token
- func TokenClaims(r *http.Request) map[string]interface{}
- func TokenHasAccess(r *http.Request, policy string) bool
- func Vars(r *http.Request) map[string]string
- type Chain
- type Configuration
- func (c *Configuration) Get(internalName string) string
- func (c *Configuration) Parse()
- func (c *Configuration) ParseEnvironment(parseAll bool)
- func (c *Configuration) RegisterMandatoryParameter(envName string, internalName string, usage string)
- func (c *Configuration) RegisterOptionalParameter(envName string, defaultValue string, internalName string, usage string)
- func (c *Configuration) RegisterParameter(envName string, defaultValue string, internalName string, mandatory bool, ...)
- type Constructor
- type EnvParameter
- type HijackerResponseWriter
- type PolicyManager
- type PrometheusHolder
- type ResponseWriter
- type Server
- type Service
- func (s *Service) Handle(pattern string, originalHandler http.Handler) *mux.Route
- func (s *Service) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) *mux.Route
- func (s *Service) SecureHandle(pattern string, originalHandler http.Handler) *mux.Route
- func (s *Service) SecureHandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) *mux.Route
- func (s *Service) Shutdown()
- func (s *Service) Start()
- func (s *Service) StatusHealthy()
- func (s *Service) StatusNotReady()
- func (s *Service) StatusReady()
- func (s *Service) StatusUnhealthy()
- func (s *Service) UnsafeHandle(pattern string, originalHandler http.Handler) *mux.Route
- func (s *Service) UnsafeHandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) *mux.Route
- type Shutdowner
- type TLSServer
- type Timer
Constants ¶
const FlagMissyControllerAddressDefault = "http://missy-controller"
FlagMissyControllerAddressDefault is a default for the missy-controller url used in the during service initialisation when given the init flag
const FlagMissyControllerUsage = "The address of the MiSSy controller"
FlagMissyControllerUsage is a usage message for the missy-controller url used in the during service initialisation when given the init flag
const PrometheusInstance key = 0
PrometheusInstance is a key for the context value of the PrometheusHolder
const RequestTimer key = 2
RequestTimer is the key for the request timer in context
const RouterInstance key = 1
RouterInstance is the key for the goilla/mux router instance in the context
Variables ¶
This section is empty.
Functions ¶
func AuthHandler ¶ added in v0.3.0
AuthHandler is a middleware to authenticating a user or machine by validating an JWT auth token passed in the header of the request
func FinalHandler ¶ added in v0.3.0
FinalHandler measures the time of the request with the help of the timestamp taken in StartTimerHandler and writes it to a Prometheus metric. It will also write a log line of the request in the log file
func IsRequestTokenValid ¶ added in v0.4.10
IsRequestTokenValid checks if request has a valid token
func IsSignedTokenValid ¶ added in v0.4.10
IsSignedTokenValid checks if provided signed token string is valid
func NewClient ¶ added in v0.3.0
NewClient returns a new http.Client with custom CA Cert if given through TLS_CACERT
func StartTimerHandler ¶
StartTimerHandler is a middleware to start a timer for the request benchmark
func TokenClaims ¶ added in v0.4.10
TokenClaims get token claims
func TokenHasAccess ¶ added in v0.3.0
TokenHasAccess checks if a valid access token contains a given policy in a context
Types ¶
type Chain ¶
type Chain struct {
// contains filtered or unexported fields
}
Chain acts as a list of http.Handler constructors. Chain is effectively immutable: once created, it will always hold the same set of constructors in the same order.
func NewChain ¶
func NewChain(constructors ...Constructor) *Chain
NewChain creates a new chain, memorizing the given list of middleware constructors. New serves no other function, constructors are only called upon a call to Then().
func (Chain) Append ¶
func (c Chain) Append(constructors ...Constructor) Chain
Append extends a chain, adding the specified constructors as the last ones in the request flow.
Append returns a new chain, leaving the original one untouched.
stdChain := alice.New(m1, m2) extChain := stdChain.Append(m3, m4) // requests in stdChain go m1 -> m2 // requests in extChain go m1 -> m2 -> m3 -> m4
func (Chain) Extend ¶
Extend extends a chain by adding the specified chain as the last one in the request flow.
Extend returns a new chain, leaving the original one untouched.
stdChain := alice.New(m1, m2) ext1Chain := alice.New(m3, m4) ext2Chain := stdChain.Extend(ext1Chain) // requests in stdChain go m1 -> m2 // requests in ext1Chain go m3 -> m4 // requests in ext2Chain go m1 -> m2 -> m3 -> m4
Another example:
aHtmlAfterNosurf := alice.New(m2) aHtml := alice.New(m1, func(h http.Handler) http.Handler { csrf := nosurf.New(h) csrf.SetFailureHandler(aHtmlAfterNosurf.ThenFunc(csrfFail)) return csrf }).Extend(aHtmlAfterNosurf) // requests to aHtml hitting nosurfs success handler go m1 -> nosurf -> m2 -> target-handler // requests to aHtml hitting nosurfs failure handler go m1 -> nosurf -> m2 -> csrfFail
func (*Chain) Final ¶
func (c *Chain) Final(ff Constructor) *Chain
Final chain defines the final piece of the chain that is executed after the middleware called with Then()
func (Chain) Then ¶
Then chains the middleware and returns the final http.Handler.
New(m1, m2, m3).Then(h)
is equivalent to:
m1(m2(m3(h)))
When the request comes in, it will be passed to m1, then m2, then m3 and finally, the given handler (assuming every middleware calls the following one).
A chain can be safely reused by calling Then() several times.
stdStack := alice.New(ratelimitHandler, csrfHandler) indexPipe = stdStack.Then(indexHandler) authPipe = stdStack.Then(authHandler)
Note that constructors are called on every call to Then() and thus several instances of the same middleware will be created when a chain is reused in this way. For proper middleware, this should cause no problems.
Then() treats nil as http.DefaultServeMux.
type Configuration ¶ added in v0.4.10
type Configuration struct { Name string `json:"name"` Environment []EnvParameter `json:"environment"` }
Configuration holds the service configuration for the MiSSy service
func Config ¶ added in v0.4.10
func Config() *Configuration
Config returns the singleton instance of the service configuration We explicitly don't want to do this on the first call of Config() to avoid race conditions, because other parts of the application register parameters in their init functions.
func (*Configuration) Get ¶ added in v0.4.10
func (c *Configuration) Get(internalName string) string
Get returns a value for a config parameter
func (*Configuration) Parse ¶ added in v0.4.10
func (c *Configuration) Parse()
Parse parses all configured environment variables according to configuration parameters and makes them accessible through internal names. It also checks if values have been set and if not sets default values. If parameter is not set but mandatory this function will collect all missing parameters in a list and exits the program with a usage message. This function can be called multiple times.
func (*Configuration) ParseEnvironment ¶ added in v0.4.10
func (c *Configuration) ParseEnvironment(parseAll bool)
ParseEnvironment allows to parse all environment parameters again, this will result in some log entries but does no harm, useful for testing if you set env vars in your tests but Parse() did already run
func (*Configuration) RegisterMandatoryParameter ¶ added in v0.4.10
func (c *Configuration) RegisterMandatoryParameter(envName string, internalName string, usage string)
RegisterMandatoryParameter is a shorthand to register a mandatory configuration parameter
func (*Configuration) RegisterOptionalParameter ¶ added in v0.4.10
func (c *Configuration) RegisterOptionalParameter(envName string, defaultValue string, internalName string, usage string)
RegisterOptionalParameter is a shorthand to register a optional configuration parameter with default value
func (*Configuration) RegisterParameter ¶ added in v0.4.10
func (c *Configuration) RegisterParameter(envName string, defaultValue string, internalName string, mandatory bool, usage string)
RegisterParameter registers a configuration parameter in the central service config
type Constructor ¶
Constructor for a piece of middleware. Some middleware use this constructor out of the box, so in most cases you can just pass somepackage.New
type EnvParameter ¶ added in v0.4.10
type EnvParameter struct { EnvName string `json:"envName"` DefaultValue string `json:"defaultValue"` InternalName string `json:"internalName"` Mandatory bool `json:"mandatory"` Usage string `json:"usage"` Value string `json:"-"` Parsed bool `json:"-"` }
EnvParameter defines how a config value is passed through an environment variable. This struct as members for default values and usage description. It also can mark the variable non-mandatory. An external system environment variable always maps to an internal name. As a guideline the internal name should refer to the module it is used in and should have sections divided by dots, e.g. "datastore.mysql.host"
type HijackerResponseWriter ¶ added in v0.3.0
type HijackerResponseWriter struct {
*ResponseWriter
}
HijackerResponseWriter is the MiSSy owned response writer which also handles Hijacker
func (*HijackerResponseWriter) Hijack ¶ added in v0.3.0
func (w *HijackerResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack wrapper for http.Hijacker interface
type PolicyManager ¶ added in v0.4.10
type PolicyManager struct { }
PolicyManager allows to validate and fetch policies from the HTTP request.
func (*PolicyManager) PolicyValidInRequest ¶ added in v0.4.10
func (p *PolicyManager) PolicyValidInRequest(policy string, req *http.Request) error
PolicyValidInRequest validates policy in HTTP request.
func (*PolicyManager) TokenPolicies ¶ added in v0.4.10
func (p *PolicyManager) TokenPolicies(req *http.Request) (map[string]interface{}, bool)
TokenPolicies returns all policies from the token in HTTP request.
type PrometheusHolder ¶
type PrometheusHolder struct {
// contains filtered or unexported fields
}
PrometheusHolder is holds an instances of globally and internally used Prometheus metrics
func NewPrometheus ¶
func NewPrometheus(serviceName string) *PrometheusHolder
NewPrometheus returns a new instance of a Prometheus holder to bind to a service
func (*PrometheusHolder) OnRequestFinished ¶
func (p *PrometheusHolder) OnRequestFinished(method string, path string, statusCode int, processTimeMillis float64)
OnRequestFinished will measure the http latency for the respective call to a missy service endpoint
type ResponseWriter ¶
type ResponseWriter struct { http.ResponseWriter // contains filtered or unexported fields }
ResponseWriter is the MiSSy owned response writer object
func (*ResponseWriter) Header ¶
func (w *ResponseWriter) Header() http.Header
Header wrapper for http.ResponseWriter interface
func (*ResponseWriter) Write ¶
func (w *ResponseWriter) Write(b []byte) (int, error)
ResponseWriter wrapper for http.ResponseWriter interface
func (*ResponseWriter) WriteHeader ¶
func (w *ResponseWriter) WriteHeader(code int)
WriteHeader overrides the original WriteHeader function to keep the status code
func (*ResponseWriter) WriteMetricsHeader ¶ added in v0.3.0
func (w *ResponseWriter) WriteMetricsHeader(code int)
WriteMetricsHeader just sets the status code for metrics and logging Useful for example for hijacked ResponseWriter where WriteHeader and Write are bypassed
type Server ¶ added in v0.3.0
type Server interface { ListenAndServe() error Shutdowner }
Server is implemented by *http.Server
type Service ¶
type Service struct { Host string Port string MetricsPort string Prometheus *PrometheusHolder Router *mux.Router MetricsRouter *mux.Router Stop chan os.Signal StateProbes struct { IsHealthy bool MuHealthy sync.Mutex IsReady bool MuReady sync.Mutex } // contains filtered or unexported fields }
Service type provides a HTTP/Rest service
func (*Service) Handle ¶
Handle is a wrapper around the original Go handle func with logging recovery and metrics Deprecated: Developers should use SecureHandle() or UnsafeHandle() explicitly
func (*Service) HandleFunc ¶
func (s *Service) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) *mux.Route
HandleFunc excepts a HanderFunc an converts it to a handler, then registers this handler Deprecated: Developers should use SecureHandleFunc() or UnsafeHandleFunc() explicitly
func (*Service) SecureHandle ¶ added in v0.3.0
SecureHandle is a wrapper around the original Go handle func with logging recovery and metrics
func (*Service) SecureHandleFunc ¶ added in v0.3.0
func (s *Service) SecureHandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) *mux.Route
SecureHandleFunc excepts a HanderFunc an converts it to a handler, then registers this handler
func (*Service) Shutdown ¶ added in v0.3.0
func (s *Service) Shutdown()
Shutdown allows to stop the HTTP Server gracefully
func (*Service) StatusHealthy ¶ added in v0.4.10
func (s *Service) StatusHealthy()
func (*Service) StatusNotReady ¶ added in v0.4.10
func (s *Service) StatusNotReady()
func (*Service) StatusReady ¶ added in v0.4.10
func (s *Service) StatusReady()
func (*Service) StatusUnhealthy ¶ added in v0.4.10
func (s *Service) StatusUnhealthy()
func (*Service) UnsafeHandle ¶ added in v0.3.0
UnsafeHandle is a wrapper around the original Go handle func with logging recovery and metrics
func (*Service) UnsafeHandleFunc ¶ added in v0.3.0
func (s *Service) UnsafeHandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) *mux.Route
UnsafeHandleFunc excepts a HanderFunc an converts it to a handler, then registers this handler
type Shutdowner ¶ added in v0.3.0
Shutdowner is implemented by *http.Server, and optionally by *http.Server.Handler