server

package
v2.0.4 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2023 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const CspHeaderName = "Content-Security-Policy"

CspHeaderName is the Content-Security-Policy HTTP-Header name

Variables

View Source
var DomainLabel = "domain"
View Source
var ServerName = &ContextKey{val: "serverName"}
View Source
var SessionIdKey = &ContextKey{val: "sessionId"}

SessionIdKey is the ContextKey under which the current sessionId can be found

View Source
var StatusLabel = "status"

Functions

func AccessLogHandler

func AccessLogHandler(next http.Handler) http.Handler

AccessLogHandler returns a http.Handler that adds access-logging on the info level.

func AccessMetricsHandler

func AccessMetricsHandler(next http.Handler, registration *PrometheusRegistration) http.Handler

AccessMetricsHandler collects the bytes send out as well as the status codes as prometheus metrics and writes them to the registry. The registerer has to be prepared via the AccessMetricsRegister function.

func AddGracefulShutdown

func AddGracefulShutdown(ctx context.Context, wg *sync.WaitGroup, shutdowner Shutdowner, timeout time.Duration)

AddGracefulShutdown intercepts the cancel function of the received ctx and calls the shutdowner.Shutdown interface instead. if timeout is not null a context with a deadline is prepared prior to the Shutdown call. It is the responsibility of the Shutdowner interface implementer to honor this context deadline. The waitgroup is incremented by one immediately and one is released when the shutdown has finished.

func Build

func Build(port int, readTimeout time.Duration, writeTimeout time.Duration, idleTimeout time.Duration,
	handler http.Handler, handlerSetups ...HandlerMiddleware) *http.Server

Build a http server from the provided options.

func CspHeaderHandler

func CspHeaderHandler(next http.Handler, variableName string) http.Handler

CspHeaderHandler replaces the nonce placerholder in the Content-Security-header

func FallbackHandler

func FallbackHandler(next http.Handler, fallbackPath string, fallbackCodes ...int) http.Handler

FallbackHandler routes the request to a fallback route on of the given HTTP fallback status codes

func HealthCheckConditionalHandler

func HealthCheckConditionalHandler(condition func() bool) http.Handler

HealthCheckConditionalHandler is a conditional healthcheck handler that returns HTTP 200 when the condition argument function returns true and HTTP 503 if not.

func HealthCheckHandler

func HealthCheckHandler() http.Handler

HealthCheckHandler is a dummy handler that always returns HTTP 200.

func NewCacheHandler

func NewCacheHandler(next http.Handler) *cacheHandler

NewCacheHandler computes and stores the hashes for all files

func RunTillWaitGroupFinishes

func RunTillWaitGroupFinishes(ctx context.Context, wg *sync.WaitGroup, server *http.Server, errChan chan<- error, timeout time.Duration)

RunTillWaitGroupFinishes runs the server argument until the WaitGroup wg finishes. Subsequently, a graceful shutdown with the given timeout argument is executed. Blocks till then.

func SessionCookieHandler

func SessionCookieHandler(next http.Handler, cookieName string, cookieTimeToLife time.Duration) http.Handler

SessionCookieHandler reads the cookieName cookie from the request and adds if to the context unter the SessionIdKey if present. If absent it generates a new sessionId and adds it to the context and the HTTP Set-Cookie Response header.

func SigTermCtx

func SigTermCtx(ctx context.Context, cancelDelay time.Duration) context.Context

SigTermCtx intercepts the syscall.SIGTERM and returns the information in the form of a wrapped context whose cancel function is called when the SIGTERM signal is received. cancelDelay adds an additional delay before actually cancelling the context. If a second SIGTERM is received, the shutdown is immediate via os.Exit(1).

func ValidateHandler

func ValidateHandler(next http.Handler) http.Handler

ValidateHandler returns HTTP 405 if the request method is not GET or HEAD. Also, pa relative paths are rejected with HTTP 400.

Types

type AngularCspReplaceConfig

type AngularCspReplaceConfig struct {
	// (secret) placeholder which will be replaced with the session id when serving
	VariableName string `json:"variable-name"`
	// Regex for which files the Variable-Name should be replaced
	FilePathPattern string `json:"file-path-regex,omitempty"`
	// Name of the session-id cookie
	CookieName string `json:"cookie-name"`
	// Max-Age setting for the session-id cookie, 30 seconds should be sufficient
	CookieMaxAge int `json:"cookie-max-age"`
}

AngularCspReplaceConfig holds the config options for fixing the syle-src CSP issue in Angular.

type Config

type Config struct {
	// Static headers to be set
	Headers           map[string]string        `json:"headers,omitempty"`
	AngularCspReplace *AngularCspReplaceConfig `json:"angular-csp-replace,omitempty"`
	// Mapping of file extension to Media-Type, needed due to https://github.com/golang/go/issues/32350
	MediaTypeMap map[string]string `json:"media-type-map,omitempty"`
	// Media-Types for which gzipping should be applied (if activated and client has set the Accept-Encoding: gzip HTTP-Header)
	GzipMediaTypes []string `json:"gzip-media-types,omitempty"`
}

Config holds the advanced server config options

func (*Config) GzipFileExtensions

func (config *Config) GzipFileExtensions() []string

GzipFileExtensions computes the file extensions relevant for gzipping.

type ContextKey

type ContextKey struct {
	// contains filtered or unexported fields
}

ContextKey is a struct used for storing relevant keys in the request context.

type CspFileHandler

type CspFileHandler struct {
	Next         http.Handler
	VariableName string
	MediaTypeMap map[string]string
	// contains filtered or unexported fields
}

CspFileHandler implements the http.Handler interface and fixes the Angular style-src CSP issue. The variableName is replaced in all response contents.

func (*CspFileHandler) ServeHTTP

func (handler *CspFileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type HandlerMiddleware

type HandlerMiddleware func(handler http.Handler) http.Handler

HandlerMiddleware wraps a received handler with another wrapper handler to add functionality

func AccessLog

func AccessLog() HandlerMiddleware

AccessLog adds an access logging middleware.

func AccessMetrics

func AccessMetrics(registration *PrometheusRegistration) HandlerMiddleware

AccessMetrics collects metrics about bytes send and response status codes and writes them to the provided prometheus registerer.

func Caching

func Caching() HandlerMiddleware

Caching adds a caching middleware handler which uses the ETag HTTP response and If-None-Match HTTP request headers. This requires that all following handler only serve static resources. Following handlers will only be called when a cache mismatch occurs.

func CspFileReplace

func CspFileReplace(config *Config) HandlerMiddleware

CspFileReplace replaces the nonce variable in all content responses and has the hard requirement that a session cookie is present in the context, see server.SessionCookie to add one.

func CspHeaderReplace

func CspHeaderReplace(config *Config) HandlerMiddleware

CspHeaderReplace replaces the nonce variable in the Content-Security-Header.

func Fallback

func Fallback(fallbackPath string, fallbackCodes ...int) HandlerMiddleware

Fallback adds a fallback route handler. THis routes the request to a fallback route on of the given HTTP fallback status codes

func H2C

func H2C(h2cPort int) HandlerMiddleware

H2C adds a middleware that supports h2c (unencrypted http2)

func Header(config *Config) HandlerMiddleware

Header adds a static HTTP header adding middleware

func Optional

func Optional(middleware HandlerMiddleware, isActive bool) HandlerMiddleware

Optional sets the middleware if the isActive condition is fulfilled

func SessionId

func SessionId(config *Config) HandlerMiddleware

SessionId adds a session cookie adding middleware

func Validate

func Validate() HandlerMiddleware

Validate adds to the validate middleware and prevent path transversal attacks by cleaning the request path.

type HeaderHandler

type HeaderHandler struct {
	Next    http.Handler
	Headers map[string]string
}

HeaderHandler implements the http.Handler interface and adds the static headers provided in the Headers map to the response.

func (*HeaderHandler) ServeHTTP

func (handler *HeaderHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type PrometheusRegistration

type PrometheusRegistration struct {
	// contains filtered or unexported fields
}

PrometheusRegistration wraps a prometheus registerer and corresponding registered types.

func AccessMetricsRegister

func AccessMetricsRegister(registerer prometheus.Registerer, prometheusNamespace string) (*PrometheusRegistration, error)

AccessMetricsRegister registrates the relevant prometheus types and returns a custom registration type

type ReplacerCollection

type ReplacerCollection struct {
	// contains filtered or unexported fields
}

ReplacerCollection is a series of replacer implementations which are used to effectively replace a given string by pre-splitting the target template.

func ReplacerCollectionFromInput

func ReplacerCollectionFromInput(data []byte, toReplace string, mediaType string) *ReplacerCollection

ReplacerCollectionFromInput constructs a replacer that prepares the input data into a template where the toReplace string will be replaced.

func (*ReplacerCollection) Replace

func (replacer *ReplacerCollection) Replace(w io.Writer, input string) error

Replace replaces the template placeholder with the input string and writes the result to the io.Writer w.

type Shutdowner

type Shutdowner interface {
	Shutdown(context.Context) error
}

Shutdowner are functions that support a Shutdown operation. It is the responsibility of the interface implementer to honor the context deadline.

Jump to

Keyboard shortcuts

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