middleware

package
v0.0.0-...-2b7dcb4 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2024 License: BSD-2-Clause Imports: 22 Imported by: 10

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultErrorHandler = func(ctx context.Context, err error, w http.ResponseWriter, r *http.Request) {
	writeError(w, err)
}

DefaultErrorHandler is an error handler that will respond with the error message and a 500 status.

View Source
var DefaultRequestIDExtractor = HeaderExtractor([]string{"X-Request-Id", "Request-Id"})

DefaultRequestIDExtractor is the default function to use to extract a request id from an http.Request.

View Source
var ErrHandlerTimeout = &handlerTimeout{"http: handler timeout"}

ErrHandlerTimeout is returned on ResponseWriter Write calls in handlers which have timed out.

View Source
var JSONReportingErrorHandler = httpx.Error
View Source
var ReportingErrorHandler = func(ctx context.Context, err error, w http.ResponseWriter, r *http.Request) {
	reporter.Report(ctx, err)
	writeError(w, err)
}

ReportingErrorHandler is an error handler that will report the error and respond with the error message and a 500 status.

View Source
var StdoutLogger = stdLogger(logger.DEBUG, os.Stdout)

Legacy interface, returns a loggerGenerator that logs at DEBUG to stdout. Use StdoutLoggerWithLevel() instead.

Functions

func DefaultUnauthorizedHandler

func DefaultUnauthorizedHandler(realm string) httpx.HandlerFunc

func HeaderExtractor

func HeaderExtractor(headers []string) func(*http.Request) string

HeaderExtractor returns a function that can extract a value from a list of headers.

func InsertLogger

func InsertLogger(h httpx.Handler, g loggerGenerator) httpx.Handler

InsertLogger returns an httpx.Handler middleware that will call f to generate a logger, then insert it into the context.

func LogTo

func LogTo(h httpx.Handler, g loggerGenerator) httpx.Handler

LogTo is an httpx middleware that wraps the handler to insert a logger and log the request to it.

func LoggerWithRequestID

func LoggerWithRequestID(ctx context.Context, r *http.Request) logger.Logger

func StdoutLoggerWithLevel

func StdoutLoggerWithLevel(lvl string) loggerGenerator

returns a loggerGenerator that generates a loggers that write to STDOUT with the level parsed from the string (eg "info") If the string isnt parsable, it defaults to "debug"

func TimeoutHandler

func TimeoutHandler(h httpx.Handler, dt time.Duration) httpx.Handler

TimeoutHandler returns a Handler that runs h with the given time limit.

The new Handler calls h.ServeHTTPContext to handle each request, but if a call runs for longer than its time limit, the handler will return an error that satisfies the timeoutError interface, to integrate with the error middleware.

After such a timeout, writes by h to its ResponseWriter will return ErrHandlerTimeout.

TimeoutHandler buffers all Handler writes to memory and does not support the Hijacker or Flusher interfaces.

NOTE This is a modified version of https://godoc.org/net/http#TimeoutHandler

func VerifySignature

func VerifySignature(cfg RequestSigningConfig, h httpx.Handler) httpx.HandlerFunc

VerifySignature wraps an httpx.Handler with a request signature check. Usage:

import "github.com/remind101/pkg/httpx"
import "github.com/remind101/pkg/httpx/middleware"
...
r := httpx.NewRouter()
keys := middleware.NewStaticSigningKeyRepositoryFromStringSlice([]string{"key_id:key_secret", "key2_id:key2_secret"})
cfg := middleware.RequestSigningConfig{ForceVerification: true, SigningKeyRepository: keys}
r.Handle("/foo", VerifySignature(cfg, myHandler)).Methods("GET")
...

See also documentation for RequestSigningConfig See https://tools.ietf.org/html/draft-cavage-http-signatures-07 for more details.

Types

type Background

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

Background is middleware that implements the http.Handler interface to inject an initial context object. Use this as the entry point from an http.Handler server.

This middleware is deprecated. There is no need to pass a context.Context to handlers anymore, since a context object is available from the request. Once we update the signature for httpx.Handler to remove the context parameter, this middleware can be removed.

func BackgroundContext

func BackgroundContext(h httpx.Handler) *Background

func (*Background) ServeHTTP

func (h *Background) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

func (*Background) ServeHTTPContext

func (h *Background) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error

type BasicAuther

type BasicAuther struct {
	User, Pass string
	Realm      string

	// The handler that will be called if the request is authorized.
	Handler httpx.Handler

	// The handler that will be called if the request is not authorized. The
	// zero value is DefaultUnauthorizedHandler
	UnauthorizedHandler httpx.Handler
}

func BasicAuth

func BasicAuth(h httpx.Handler, user, pass, realm string) *BasicAuther

func (*BasicAuther) ServeHTTPContext

func (a *BasicAuther) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error

type BasicRecovery

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

func BasicRecover

func BasicRecover(h httpx.Handler) *BasicRecovery

func (*BasicRecovery) ServeHTTPContext

func (h *BasicRecovery) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) (err error)

ServeHTTPContext implements the httpx.Handler interface. It recovers from panics and returns an error for upstream middleware to handle.

type Error

type Error struct {
	// ErrorHandler is a function that will be called when a handler returns
	// an error.
	ErrorHandler ErrorHandlerFunc
	// contains filtered or unexported fields
}

Error is an httpx.Handler that will handle errors with an ErrorHandler.

func HandleError

func HandleError(h httpx.Handler, f ErrorHandlerFunc) *Error

HandleError returns a new Error middleware that uses f as the ErrorHandler.

func NewError

func NewError(h httpx.Handler) *Error

func (*Error) ServeHTTPContext

func (h *Error) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error

ServeHTTPContext implements the httpx.Handler interface.

type ErrorHandlerFunc

type ErrorHandlerFunc func(context.Context, error, http.ResponseWriter, *http.Request)
type Header struct {
	// contains filtered or unexported fields
}

func ExtractHeader

func ExtractHeader(h httpx.Handler, header string) *Header

func (*Header) ServeHTTPContext

func (h *Header) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error

type Logger

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

Logger is middleware that logs the request details to the logger.Logger embedded within the context.

func Log

func Log(h httpx.Handler) *Logger

func (*Logger) ServeHTTPContext

func (h *Logger) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error

type OpentracingTracer

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

func OpentracingTracing

func OpentracingTracing(h httpx.Handler, router *httpx.Router) *OpentracingTracer

func (*OpentracingTracer) ServeHTTPContext

func (h *OpentracingTracer) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error

type Recovery

type Recovery struct {
	// Reporter is a Reporter that will be inserted into the context. It
	// will also be used to report panics.
	reporter.Reporter
	// contains filtered or unexported fields
}

Recovery is a middleware that will recover from panics and return the error.

func Recover

func Recover(h httpx.Handler, r reporter.Reporter) *Recovery

func (*Recovery) ServeHTTPContext

func (h *Recovery) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) (err error)

ServeHTTPContext implements the httpx.Handler interface. It recovers from panics and returns an error for upstream middleware to handle.

type Reporter

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

Reporter is a middleware that adds a Reporter to the request context and adds the request info to the reporter context.

func WithReporter

func WithReporter(h httpx.Handler, r reporter.Reporter) *Reporter

func (*Reporter) ServeHTTPContext

func (m *Reporter) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error

type RequestID

type RequestID struct {
	// Extractor is a function that can extract a request id from an
	// http.Request. The zero value is a function that will pull a request
	// id from the `X-Request-ID` or `Request-ID` headers.
	Extractor func(*http.Request) string
	// contains filtered or unexported fields
}

RequestID is middleware that extracts a request id from the headers and inserts it into the context.

func ExtractRequestID

func ExtractRequestID(h httpx.Handler) *RequestID

func (*RequestID) ServeHTTPContext

func (h *RequestID) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error

ServeHTTPContext implements the httpx.Handler interface. It extracts a request id from the headers and inserts it into the context.

type RequestSignatureError

type RequestSignatureError struct {
	KeyID string
	// contains filtered or unexported fields
}

RequestSignatureError should be used in your error handling middleware. Usage:

import "github.com/tomasen/realip"
import "github.com/remind101/pkg/logger"
import "github.com/remind101/pkg/metrics"
import "github.com/remind101/pkg/httpx/middleware"
...
switch err := errors.Cause(err).(type) {
  case middleware.RequestSignatureError:
    remoteAddr := realip.RealIP(r)
    metrics.Count("authentication.failure", 1, map[string]string{"keyid": err.KeyID, "remote_ip": remoteAddr}, 1.0)
    logger.Error(ctx, "authentication failure", "keyid", err.KeyID, "remote_ip", remoteAddr, "err", err.Error())
    w.WriteHeader(403)
    fmt.Fprintf(w, `{"error":"request signature verification error"}`)
  ...
}
...

func (RequestSignatureError) Error

func (e RequestSignatureError) Error() string

type RequestSigningConfig

type RequestSigningConfig struct {
	ForceVerification bool
	SigningKeyRepository
}

RequestSigningConfig contains configuration for request signing middleware. ForceVerification - when true, rejects all requests with absent/malformed/invalid request signature header;

when false, allows requests with absent/malformed request signature header, rejects
  requests with invalid signature.

SigningKeyRepository - an implementation of SigningKeyRepository.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	// Status returns the status code of the response or 200 if the response has not been written.
	Status() int
}

ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response.

func NewResponseWriter

func NewResponseWriter(rw http.ResponseWriter) ResponseWriter

NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter

type SigningKeyRepository

type SigningKeyRepository interface {
	GetKey(keyID string) (string, error)
}

SigningKeyRepository stores request signing keys.

type StaticSigningKeyRepository

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

StaticSigningKeyRepository implements SigningKeyRepository and stores pairs of key ids and secrets in memory.

func NewStaticSigningKeyRepository

func NewStaticSigningKeyRepository(keys map[string]string) *StaticSigningKeyRepository

NewStaticSigningKeyRepository creates a SigningKeyRepository from a string map where keys are key ids and values are HMAC secrets.

func NewStaticSigningKeyRepositoryFromStringSlice

func NewStaticSigningKeyRepositoryFromStringSlice(idkeys []string) *StaticSigningKeyRepository

NewStaticSigningKeyRepositoryFromStringSlice creates a SigningKeyRepository from a string slice in form of []string{"keyId:keyValue"}, which can be used with StringSlice from https://github.com/urfave/cli.

func (*StaticSigningKeyRepository) GetKey

func (r *StaticSigningKeyRepository) GetKey(keyID string) (string, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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