server

package
v1.11.2 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2023 License: MIT Imports: 26 Imported by: 1

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 RequestIdKey = &ContextKey{val: "requestId"}

RequestIdKey is the context key used for storing the request id in the request context.

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"
View Source
var TimerKey = &ContextKey{val: "timerStart"}

TimerKey is the ContextKey under which the timing start time.Time can be found

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 added in v1.9.0

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 added in v1.2.0

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 FileServerHandler

func FileServerHandler(fs fs.FS, zipfs fs.FS, fallbackFilepath string, config *Config) http.Handler

FileServerHandler implements the actual fileserver logic. zipfs can be set to nil if no pre-zipped file have been prepared.

func GzipHandler

func GzipHandler(next http.Handler, compressionLevel int, gzipMediaTypes []string) http.Handler

GzipHandler is a handler that compressed responses if the HTTP Content-Type response header is part of the gzipMediaTypes and if the request has the Accept-Encoding=gzip HTTP request Header set.

func HealthCheckConditionalHandler added in v1.1.0

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 RequestIdToCtxHandler

func RequestIdToCtxHandler(next http.Handler) http.Handler

RequestIdToCtxHandler generates a random request-id and adds it to the request context under the RequestIdKey.

func RunTillWaitGroupFinishes added in v1.4.2

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 added in v1.2.0

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 TimerStartToCtxHandler

func TimerStartToCtxHandler(next http.Handler) http.Handler

TimerStartToCtxHandler starts a timer and adds it to the request context under the TimerKey key

func ValidateCleanHandler

func ValidateCleanHandler(next http.Handler) http.Handler

ValidateCleanHandler returns HTTP 405 if the request method is not GET or HEAD. Also, 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
	FileNamePattern string `json:"file-name-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 CspReplaceHandler

type CspReplaceHandler struct {
	Next           http.Handler
	Filesystem     fs.ReadFileFS
	FileNamePatter *regexp.Regexp
	MediaTypeMap   map[string]string
	VariableName   string
	// contains filtered or unexported fields
}

CspReplaceHandler implements the http.Handler interface and fixes the Angular style-src CSP issue. The variableName is replaced in files that match the FileNamePattern as well as in the Content-Security-Policy header.

func (*CspReplaceHandler) ServeHTTP

func (handler *CspReplaceHandler) 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 added in v1.9.0

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 CspReplace

func CspReplace(config *Config, filesystem fs.ReadFileFS) HandlerMiddleware

CspReplace has the hard requirement that a session cookie is present in the context, see server.SessionCookie to add one.

func Gzip

func Gzip(config *Config, compressionLevel int) HandlerMiddleware

Gzip adds an on-demand gzipping middleware. Gzip is only applied when the Accept-Encoding: gzip HTTP request header is present and the Content-Type of the response matches the config options.

func H2C added in v1.11.0

func H2C(h2cPort int) HandlerMiddleware

H@C 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 RequestID

func RequestID() HandlerMiddleware

RequestID adds a middleware that adds a randomly generated request id to the request context.

func SessionId

func SessionId(config *Config) HandlerMiddleware

SessionId adds a session cookie adding middleware

func Timer

func Timer() HandlerMiddleware

Timer adds a middleware that adds a started timer to the request context for time measuring purposes.

func ValidateClean

func ValidateClean() HandlerMiddleware

ValidateClean 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 added in v1.9.3

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

PrometheusRegistration wraps a prometheus registerer and corresponding registered types.

func AccessMetricsRegister added in v1.9.3

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) (*ReplacerCollection, error)

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 added in v1.2.0

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