http

package
v1.2.9 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2023 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HeaderAllowHeaders = "Access-Control-Allow-Headers"
	HeaderAllowMethods = "Access-Control-Allow-Methods"
	HeaderAllowOrigin  = "Access-Control-Allow-Origin"
	HeaderExposeHeader = "Access-Control-Expose-Headers"
	HeaderAccessMaxAge = "Access-Control-Max-Age"
)

Headers

View Source
const (
	// NoPrintStackBodyString is the body content returned when HTTP stack printing is suppressed
	NoPrintStackBodyString = "500 Internal Server Error"
)

Variables

View Source
var (
	ErrNotHTTPRequest  = errors.New("missmatch type, request should be *http.Request")
	ErrNotHTTPResponse = errors.New("mismatch type, response should be *http.Response")
)

Standard HTTP Errors

Functions

func Chain

func Chain(inner net_http.Handler, filters ...Filter) net_http.Handler

func NewBeforeDecorator

func NewBeforeDecorator(cx context.Context, req *http.Request) context.Context

NewBeforeDecorator is Before that is called before every request is processed by the endpoint The decorations done here are used by the finalizer to read the context and take options on it

func NewHandler

func NewHandler(fn Handler, opts ...HandlerOption) net_http.Handler

NewHandler returns http.Handler

func NewResponse

func NewResponse(req *net_http.Request, opts ...ResponseOption) *net_http.Response

NewResponse returns a new net/http.Response based on incoming request and the available options passed to it

func NoopBefore

func NoopBefore(cx context.Context, _ *http.Request) context.Context

NoopBefore is Before which has no operation

func NoopMiddleware

func NoopMiddleware(next endpoint.Endpoint) endpoint.Endpoint

NoopMiddleware is middleware that does nothing It is returned if a given middleware is not enabled

Types

type AfterFunc

type AfterFunc kit_http.ServerResponseFunc

type BeforeFunc

type BeforeFunc kit_http.RequestFunc

type ContextKey

type ContextKey int

ContextKey is key for context

const (
	ContextKeyRequestMethod ContextKey = iota
	ContextKeyRequestURI
	ContextKeyRequestPath
	ContextKeyRequestProto
	ContextKeyRequestHost
	ContextKeyRequestRemoteAddr
	ContextKeyRequestXForwardedFor
	ContextKeyRequestXForwardedProto
	ContextKeyRequestAuthorization
	ContextKeyRequestReferer
	ContextKeyRequestUserAgent
	ContextKeyRequestXRequestID
	ContextKeyRequestAccept
	ContextKeyResponseHeaders
	ContextKeyResponseSize
)

ContextKeys

type Decoder

type Decoder func(context.Context, *net_http.Request) (interface{}, error)

Decoder provides method to decode the body of the Request

func NewDefaultDecoder

func NewDefaultDecoder() Decoder

NewDefaultDecoder returns default decoder for http

func NopRequestDecoder

func NopRequestDecoder() Decoder

NopRequestDecoder is no operation Decoder for the request

type Encoder

type Encoder func(context.Context, net_http.ResponseWriter, interface{}) error

Encoder denotes the Encoder used to write the data on stream after reading the interface

func NewDefaultEncoder

func NewDefaultEncoder() Encoder

NewDefaultEncoder returns a default Encoder used by http

func NewDefaultJSONEncoder

func NewDefaultJSONEncoder() Encoder

NewDefaultJSONEncoder encodes the response in JSON

type ErrorEncoder

type ErrorEncoder func(context.Context, error, net_http.ResponseWriter)

ErrorEncoder defines the Encoder that handles error

type ErrorHandler

type ErrorHandler interface {
	transport.ErrorHandler
}

ErrorHandler wraps onn top of transport.ErrorHandler and provides a hook for diagnostic purpose

type Filter

type Filter func(net_http.Handler) net_http.Handler

func DecoratedPanicRecoveryFilter

func DecoratedPanicRecoveryFilter(logger log.Logger, opts ...RecoveryFilterOption) Filter

func ElasticApm

func ElasticApm() Filter

elastic apm filter wrapper

func PanicRecovery

func PanicRecovery(logger log.Logger) Filter

very basic panic recovery filter

type HTMLPanicFormatter

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

func (*HTMLPanicFormatter) FormatPanicError

func (t *HTMLPanicFormatter) FormatPanicError(rw net_http.ResponseWriter, r *net_http.Request, infos *PanicInformation)

type Handler

type Handler endpoint.Endpoint

Handler is wrapper on top of endpoint.Endpoint

func Wrap

func Wrap(hn Handler, mws ...Middleware) Handler

Wrap wraps around middleware

type HandlerFunc

type HandlerFunc func(ctx context.Context, req *net_http.Request) (*net_http.Response, error)

HandlerFunc defines the default wrapper for request/response handling in http transport. By default we can't support the default net_http.handler interface as the `ServeHTTP(r *http.Request, rw http.ResponseWriter)` func has rw built in which overlaps our abstraction This here instead gives us the ability to expose this as endpoint.Endpoint and use it in the go-kit chain

type HandlerOption

type HandlerOption func(*handler)

HandlerOption provides ways to modify the handler

func HandlerWithAfterFunc

func HandlerWithAfterFunc(fn AfterFunc) HandlerOption

HandlerWithAfterFunc returns a request handler with customer after function

func HandlerWithBeforeFunc

func HandlerWithBeforeFunc(fn BeforeFunc) HandlerOption

HandlerWithBeforeFunc returns a request handler with customer before function

func HandlerWithDecoder

func HandlerWithDecoder(fn Decoder) HandlerOption

HandlerWithDecoder returns a request handler with a customer decoer function

func HandlerWithEncoder

func HandlerWithEncoder(fn Encoder) HandlerOption

HandlerWithEncoder returns a request handler with customer encoder function

func HandlerWithEndpointMiddleware

func HandlerWithEndpointMiddleware(fn endpoint.Middleware) HandlerOption

HandlerWithEndpointMiddleware provides an ability to add a middleware of the base type

func HandlerWithErrorEncoder

func HandlerWithErrorEncoder(fn ErrorEncoder) HandlerOption

HandlerWithErrorEncoder returns a request handler with a customer error encoder function

func HandlerWithErrorhandler

func HandlerWithErrorhandler(fn ErrorHandler) HandlerOption

HandlerWithErrorhandler returns a request handler with a custom error handler

func HandlerWithFilter

func HandlerWithFilter(f Filter) HandlerOption

HandlerWithFilter provides an ability to add a

func HandlerWithMiddleware

func HandlerWithMiddleware(fn Middleware) HandlerOption

HandlerWithMiddleware sets middleware for request

func NewCORSHandlerOption

func NewCORSHandlerOption() HandlerOption

NewCORSHandlerOption sets default CORS headers for a request

func NewCustomCORSHandlerOption

func NewCustomCORSHandlerOption(
	origin string,
	maxage int,
	methods []string,
	headers []string,
	exposeHeaders []string,
) HandlerOption

NewCustomCORSHandlerOption sets CORS header for a given request

func NewDeleteHeaderHandlerOption

func NewDeleteHeaderHandlerOption(headers ...string) HandlerOption

NewDeleteHeaderHandlerOption deletes the headers from net_http.Request before it is sent to HandlerFunc

func NewErrorEncoderHandlerOptions

func NewErrorEncoderHandlerOptions(fn ErrorEncoder) HandlerOption

NewErrorEncoderHandlerOptions provides a handler specific error encoder

func NewGoKitDecoderHandlerOption

func NewGoKitDecoderHandlerOption(fn kit_http.DecodeRequestFunc) HandlerOption

NewGoKitDecoderHandlerOption sets a decoder of a type kit_http.DecodeRequestFunc

func NewGoKitEncoderHandlerOption

func NewGoKitEncoderHandlerOption(fn kit_http.EncodeResponseFunc) HandlerOption

NewGoKitEncoderHandlerOption provides option to encode the request

func NewGoKitErrorEncoderHandlerOption

func NewGoKitErrorEncoderHandlerOption(fn kit_http.ErrorEncoder) HandlerOption

NewGoKitErrorEncoderHandlerOption provides an option to set error encoder for handler or transport based on Go-Kit's ErrorEncoder

func NewPopulateRequestContextRequestFunc

func NewPopulateRequestContextRequestFunc() HandlerOption

NewPopulateRequestContextRequestFunc populates the context with properties extracted from net_http.Request

func NewRequestIDHandlerOption

func NewRequestIDHandlerOption(customHeaders ...string) HandlerOption

NewRequestIDHandlerOption returns a HandlerOption for simple Request ID generation

func NewServerHandlerOption

func NewServerHandlerOption(name, version string) HandlerOption

NewServerHandlerOption sets Server Header for the Request

func NewSetRequestHeader

func NewSetRequestHeader(key, val string) HandlerOption

NewSetRequestHeader sets the request header

func NewSetResponseHeader

func NewSetResponseHeader(key, val string) HandlerOption

NewSetResponseHeader sets the response header

func NewTraceLoggerFinalizerHandlerOption

func NewTraceLoggerFinalizerHandlerOption(logger log.Logger) HandlerOption

NewTraceLoggerFinalizerHandlerOption returns a HandlerOption for simple trace logging

type Metricser

type Metricser interface {
	Counter(prefix, name string) metrics.Counter

	Histogram(prefix, name string) metrics.Histogram

	Handler() net_http.Handler
}

Metricser is wrapper for supported metrics agents

func NewDefaultMetricer

func NewDefaultMetricer(namespace string, fields []string) Metricser

NewDefaultMetricer returns metricer's default implementation

type Middleware

type Middleware endpoint.Middleware

Middleware defines the middleware for request

type Mux

type Mux interface {
	// ServeHTTP
	net_http.Handler

	// Default Handler Method is all that is needed
	Handler(method, url string, fn net_http.Handler)
}

Mux defines the standard Multiplexer for http Request

func NewDefaultMux added in v1.2.9

func NewDefaultMux(opts ...MuxOption) Mux

type MuxOption added in v1.2.9

type MuxOption func(*muxer)

func WithDefaultMuxNoTrailingRedirect added in v1.2.9

func WithDefaultMuxNoTrailingRedirect() MuxOption

type PanicFormatter

type PanicFormatter interface {
	// FormatPanicError output the stack for a given answer/response.
	// In case the the middleware should not output the stack trace,
	// the field `Stack` of the passed `PanicInformation` instance equals `[]byte{}`.
	FormatPanicError(rw net_http.ResponseWriter, r *net_http.Request, infos *PanicInformation)
}

PanicFormatter is an interface on object can implement to be able to output the stack trace

type PanicInformation

type PanicInformation struct {
	RecoveredPanic interface{}
	Stack          []byte
	Request        *net_http.Request
}

PanicInformation contains all elements for printing stack informations.

func (*PanicInformation) RequestDescription

func (p *PanicInformation) RequestDescription() string

RequestDescription returns a printable description of the url

func (*PanicInformation) StackAsString

func (p *PanicInformation) StackAsString() string

StackAsString returns a printable version of the stack

type Params

type Params map[string]string

Params is wrapper on top of params in Context

func Parameters

func Parameters(r *http.Request) Params

Parameters returns the request parameters extracted from http.Request

func (Params) ByName

func (p Params) ByName(name string) string

ByName returns the URL Parameter by Name

type Recovery

type Recovery struct {
	Logger           log.Logger
	PrintStack       bool
	LogStack         bool
	PanicHandlerFunc func(*PanicInformation)
	StackAll         bool
	StackSize        int
	Formatter        PanicFormatter
}

Recovery is a Negroni middleware that recovers from any panics and writes a 500 if there was one.

func NewRecovery

func NewRecovery(logger log.Logger, options ...RecoveryFilterOption) *Recovery

NewRecovery returns a new instance of Recovery

type RecoveryFilterOption

type RecoveryFilterOption func(*Recovery)

func WithCustomFormatterRecoveryFilterOption

func WithCustomFormatterRecoveryFilterOption(fmt PanicFormatter) RecoveryFilterOption

WithCustomFormatterRecoveryFilterOption sets a custom formatter for recovery to use

func WithDevelopmentDefaultsRecoveryFilterOption

func WithDevelopmentDefaultsRecoveryFilterOption() RecoveryFilterOption

WithDevelopmentDefaultsRecoveryFilterOption configures the Recovery filter for default development configuration

func WithPanicHandlerFuncRecoveryFilterOption

func WithPanicHandlerFuncRecoveryFilterOption(fn func(*PanicInformation)) RecoveryFilterOption

WithPanicHandlerFuncRecoveryFilterOption lets the panic handler function to be configured

func WithPrintStackRecoveryFilterOption

func WithPrintStackRecoveryFilterOption(ps bool) RecoveryFilterOption

WithPrintStackRecoveryFilterOption lets you configure if the stack is to be printed or not

func WithProductionDefaultsRecoveryFilterOption

func WithProductionDefaultsRecoveryFilterOption() RecoveryFilterOption

WithProductionDefaultsRecoveryFilterOption configures the Recovery filter for default Production configuration

func WithStackSizeRecoveryFilterOption

func WithStackSizeRecoveryFilterOption(ss int) RecoveryFilterOption

WithStackSizeRecoveryFilterOption configures the stack size returned

type ResponseOption

type ResponseOption func(*net_http.Response)

ResponseOption defines the options which modify the net/http Response

func ResponseWithBytes

func ResponseWithBytes(bt []byte) ResponseOption

ResponseWithBytes provide option to update the response body with Bytes data

func ResponseWithCode

func ResponseWithCode(code int) ResponseOption

ResponseWithCode provides option to update the status code for the reponse

func ResponseWithReader

func ResponseWithReader(reader io.Reader) ResponseOption

ResponseWithReader provies option to update the body of the response with a custom reader

type TextPanicFormatter

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

func (*TextPanicFormatter) FormatPanicError

func (t *TextPanicFormatter) FormatPanicError(rw net_http.ResponseWriter, r *net_http.Request, infos *PanicInformation)

type Transport

type Transport struct {
	*net_http.Server
	// contains filtered or unexported fields
}

Transport is a wrapper around net_http.Server with sane defaults dimfeld/httptreemux is used as default multiplexer and Go-Kit's http transport is used as default request handler

func NewTransport

func NewTransport(
	host, port string,
	options ...TransportOption,
) (*Transport, error)

NewTransport returns a new transport

func (*Transport) Close

func (tr *Transport) Close() error

Close shuts down Transport

func (*Transport) DELETE

func (tr *Transport) DELETE(
	url string,
	fn Handler,
	options ...HandlerOption,
)

DELETE provides flexible interface for handling request for delete method it exposes a structured logical break up of the function handling the request. breakup consists of - decoder (decodes the request & converts to business object) - endpoint (handles the business object, and returns a result in business object ) - encoder (converts business object into response)

func (*Transport) Delete

func (tr *Transport) Delete(url string, fn HandlerFunc, options ...HandlerOption)

Delete handles DELETE request

func (*Transport) GET

func (tr *Transport) GET(
	uri string,
	fn Handler,
	options ...HandlerOption,
)

GET provides flexible interface for handling request for GET method It exposes a structured logical break up of the function handling the request. Breakup consists of - decoder (decodes the request & converts to business object) - endpoint (handles the business object, and returns a result in business object ) - encoder (converts business object into response)

func (*Transport) Get

func (tr *Transport) Get(url string, fn HandlerFunc, options ...HandlerOption)

Get handles GET request

func (*Transport) HANDLE

func (tr *Transport) HANDLE(met, url string, fn Handler, options ...HandlerOption)

HANDLE gives a generic method agnostic way of binding handler to the request

func (*Transport) HEAD

func (tr *Transport) HEAD(
	url string,
	fn Handler,
	options ...HandlerOption,
)

HEAD provides flexible interface for handling request for head method it exposes a structured logical break up of the function handling the request. breakup consists of - decoder (decodes the request & converts to business object) - endpoint (handles the business object, and returns a result in business object ) - encoder (converts business object into response)

func (*Transport) Handle

func (tr *Transport) Handle(method, url string, fn HandlerFunc, options ...HandlerOption)

Handle is generic method to allow custom bindings of URL with a method and it's handler

func (*Transport) Head

func (tr *Transport) Head(url string, fn HandlerFunc, options ...HandlerOption)

Head handles HEAD request

func (*Transport) Mux

func (tr *Transport) Mux() Mux

Mux returns the default multiplexer

func (*Transport) OPTION

func (tr *Transport) OPTION(
	url string,
	fn Handler,
	options ...HandlerOption,
)

OPTION provides flexible interface for handling request for option method it exposes a structured logical break up of the function handling the request. breakup consists of - decoder (decodes the request & converts to business object) - endpoint (handles the business object, and returns a result in business object ) - encoder (converts business object into response)

func (*Transport) Open

func (tr *Transport) Open() error

Open starts the Transport

func (*Transport) Options

func (tr *Transport) Options(url string, fn HandlerFunc, options ...HandlerOption)

Options handles OPTIONS request

func (*Transport) PATCH

func (tr *Transport) PATCH(
	url string,
	fn Handler,
	options ...HandlerOption,
)

PATCH provides flexible interface for handling request for patch method it exposes a structured logical break up of the function handling the request. breakup consists of - decoder (decodes the request & converts to business object) - endpoint (handles the business object, and returns a result in business object ) - encoder (converts business object into response)

func (*Transport) POST

func (tr *Transport) POST(
	url string,
	fn Handler,
	options ...HandlerOption,
)

POST provides flexible interface for handling request for post method it exposes a structured logical break up of the function handling the request. breakup consists of - decoder (decodes the request & converts to business object) - endpoint (handles the business object, and returns a result in business object ) - encoder (converts business object into response)

func (*Transport) PUT

func (tr *Transport) PUT(
	url string,
	fn Handler,
	options ...HandlerOption,
)

PUT provides flexible interface for handling request for put method it exposes a structured logical break up of the function handling the request. breakup consists of - decoder (decodes the request & converts to business object) - endpoint (handles the business object, and returns a result in business object ) - encoder (converts business object into response)

func (*Transport) Patch

func (tr *Transport) Patch(url string, fn HandlerFunc, options ...HandlerOption)

Patch handles PATCH request

func (*Transport) Post

func (tr *Transport) Post(url string, fn HandlerFunc, options ...HandlerOption)

Post handles POST request

func (*Transport) Put

func (tr *Transport) Put(url string, fn HandlerFunc, options ...HandlerOption)

Put handles PUT request

func (*Transport) TRACE

func (tr *Transport) TRACE(
	url string,
	fn Handler,
	options ...HandlerOption,
)

TRACE provides flexible interface for handling request for trace method it exposes a structured logical break up of the function handling the request. breakup consists of - decoder (decodes the request & converts to business object) - endpoint (handles the business object, and returns a result in business object ) - encoder (converts business object into response)

func (*Transport) Trace

func (tr *Transport) Trace(url string, fn HandlerFunc, options ...HandlerOption)

Trace handles TRACE request

type TransportOption

type TransportOption func(*Transport)

TransportOption sets options parameters to Transport

func TransportWithFilter

func TransportWithFilter(f Filter) TransportOption

TransportWithFilter sets up filters for the Transport

func WithErrorEncoder

func WithErrorEncoder(fn ErrorEncoder) TransportOption

WithErrorEncoder sets error handler for the error generated by the request

func WithFullDefaults

func WithFullDefaults() TransportOption

WithFullDefaults sets default ServerOption, used by every request handler It sets following filters for the request

  • RequestID
  • CORS
  • DefaultErrorHandler
  • DefaultTranceLogger (using transport.Logger)

func WithHandlerOption

func WithHandlerOption(options ...HandlerOption) TransportOption

WithHandlerOption overrides the default HandlerOption for the transport

func WithLogger

func WithLogger(logger log.Logger) TransportOption

WithLogger sets custom logger for Transport

func WithMetricser

func WithMetricser(metricer Metricser) TransportOption

WithMetricser supports adding metricer to Transport

func WithMonitors

func WithMonitors(monitors []string) TransportOption

WithMonitors appends to a default list of monitor endpoint supported by Transport

func WithMux

func WithMux(mux Mux) TransportOption

WithMux sets the multiplexer for transport

func WithMuxOption added in v1.2.9

func WithMuxOption(opt MuxOption) TransportOption

WithMuxOption allows additional customisations of Multiplexer

func WithTimeout

func WithTimeout(idle, write, read time.Duration) TransportOption

WithTimeout sets the custom net_http.Server timeout for the Transport

func WithTransportErrorEncoder

func WithTransportErrorEncoder(fn ErrorEncoder) TransportOption

WithTransportErrorEncoder lets us put a custom error encoder for the Transport applicable at Transport level. There is a provision to do this per handler using NewErrorEncoder, however if a handler doesn't have an error encoder this will be used as default If any Handler doesn't have an error encoder defined when throwing an error this error encoder is used

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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