swrv

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2023 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ContentTypeApplicationGZip        = "application/gzip"
	ContentTypeApplicationJSON        = "application/json"
	ContentTypeApplicationLDJSON      = "application/ld+json"
	ContentTypeApplicationOctetStream = "application/octet-stream"
	ContentTypeApplicationPDF         = "application/pdf"
	ContentTypeApplicationRTF         = "application/rtf"
	ContentTypeApplicationXML         = "application/xml"
	ContentTypeApplicationZip         = "application/zip"

	ContentTypeAudioAAC  = "audio/aac"
	ContentTypeAudioMidi = "audio/midi"
	ContentTypeAudioMP3  = "audio/mpeg"
	ContentTypeAudioOGG  = "audio/ogg"
	ContentTypeAudioWebA = "audio/webm"

	ContentTypeFontOTF = "font/otf"
	ContentTypeFontTTF = "font/ttf"

	ContentTypeImageBMP  = "image/bmp"
	ContentTypeImageGif  = "image/gif"
	ContentTypeImageJpeg = "image/jpeg"
	ContentTypeImageSVG  = "image/svg+xml"
	ContentTypeImageTiff = "image/tiff"
	ContentTypeImageWebP = "image/webp"

	ContentTypeTextCSS        = "text/css"
	ContentTypeTextCSV        = "text/csv"
	ContentTypeTextHTML       = "text/html"
	ContentTypeTextJavascript = "text/javascript"
	ContentTypeTextPlain      = "text/plain"

	ContentTypeVideoMP4  = "video/mp4"
	ContentTypeVideoMpeg = "video/mpeg"
	ContentTypeVideoWebM = "video/webm"
)
View Source
const (
	HeaderAccept                        = "Accept"
	HeaderAcceptRanges                  = "Accept-Ranges"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAge                           = "Age"
	HeaderAllow                         = "Allow"
	HeaderAuthorization                 = "Authorization"
	HeaderCacheControl                  = "Cache-Control"
	HeaderConnection                    = "Connection"
	HeaderContentDisposition            = "Content-Disposition"
	HeaderContentEncoding               = "Content-Encoding"
	HeaderContentLanguage               = "Content-Language"
	HeaderContentLength                 = "Content-Length"
	HeaderContentLocation               = "Content-Location"
	HeaderContentRange                  = "Content-Range"
	HeaderContentType                   = "Content-Type"
	HeaderCookie                        = "Cookie"
	HeaderDate                          = "Date"
	HeaderETag                          = "ETag"
	HeaderExpect                        = "Expect"
	HeaderExpires                       = "Expires"
	HeaderForwarded                     = "Forwarded"
	HeaderFrom                          = "From"
	HeaderHost                          = "Host"
	HeaderIfRange                       = "If-Range"
	HeaderLastModified                  = "Last-Modified"
	HeaderLocation                      = "Location"
	HeaderRange                         = "Range"
	HeaderReferer                       = "Referer"
	HeaderRefererPolicy                 = "RefererPolicy"
	HeaderServer                        = "Server"
	HeaderSetCookie                     = "Set-Cookie"
	HeaderOrigin                        = "Origin"
	HeaderTimingAllowOrigin             = "Timing-Allow-Origin"
	HeaderTrailer                       = "Trailer"
	HeaderTransferEncoding              = "Transfer-Encoding"
	HeaderUpgrade                       = "Upgrade"
	HeaderUserAgent                     = "User-Agent"
	HeaderVary                          = "Vary"
	HeaderVia                           = "Via"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type ControllerSpec

type ControllerSpec interface {
	// GetPath returns the URL path for the controller.
	GetPath() string

	// GetHandler returns the handler instance for the controller.
	GetHandler() RequestHandler

	// WithRequestFilters appends controller-specific request filters that will be
	// applied to incoming requests after the global request filters set on the
	// parent Server instance.
	WithRequestFilters(filters ...RequestFilter) ControllerSpec

	// GetRequestFilters returns this controller's controller-specific
	// RequestFilter instances.
	GetRequestFilters() []RequestFilter

	// WithResponseFilters appends controller-specific response filters that will
	// be applied to outgoing responses after the global response filters set on
	// the parent Server instance.
	WithResponseFilters(filters ...ResponseFilter) ControllerSpec

	// GetResponseFilters returns this controller's controller-specific
	// ResponseFilter instances.
	GetResponseFilters() []ResponseFilter

	// ForMethods sets the HTTP methods that the built controller will listen for.
	//
	// If set, the controller will only be called for matching HTTP methods.
	//
	// If unset, the controller will be called for any HTTP method.
	ForMethods(methods ...string) ControllerSpec

	// GetMethods returns the list of HTTP methods that the controller will listen
	// for.
	GetMethods() []string

	// GetRequiredHeaders returns the header requirements for this controller.
	//
	// The built controller will only be called for requests containing headers
	// that match the given requirements.
	GetRequiredHeaders() map[string]string

	// WithRequiredHeader sets a header requirement for request matching.  Only
	// requests that contain the given header set to the given value will be
	// matched and forwarded to this controller.
	//
	// If the given value string is empty, the matcher will match any value set
	// on the target header.
	WithRequiredHeader(header, value string) ControllerSpec
}

ControllerSpec defines a specification for a controller that will be built for the parent Server.

func NewController

func NewController(path string, handler RequestHandler) ControllerSpec

NewController returns a new ControllerSpec instance which may be used to construct a controller for handling HTTP requests.

type ErrorControllerSpec

type ErrorControllerSpec interface {
	// GetHandler returns the handler instance for the controller.
	GetHandler() RequestHandler

	// WithRequestFilters appends controller-specific request filters that will be
	// applied to incoming requests after the global request filters set on the
	// parent Server instance.
	WithRequestFilters(filters ...RequestFilter) ErrorControllerSpec

	// GetRequestFilters returns this controller's controller-specific
	// RequestFilter instances.
	GetRequestFilters() []RequestFilter

	// WithResponseFilters appends controller-specific response filters that will
	// be applied to outgoing responses after the global response filters set on
	// the parent Server instance.
	WithResponseFilters(filters ...ResponseFilter) ErrorControllerSpec

	// GetResponseFilters returns this controller's controller-specific
	// ResponseFilter instances.
	GetResponseFilters() []ResponseFilter
}

ErrorControllerSpec defines a simplified ControllerSpec type which may be used to construct 404 or 405 error handlers.

func NewErrorController

func NewErrorController(handler RequestHandler) ErrorControllerSpec

NewErrorController constructs a new ErrorControllerSpec instance which may be used to construct an error handling controller for 404 or 405 errors.

type MatcherFn

type MatcherFn = func(object any) bool

MatcherFn defines a function that may be used as a body object matcher in an ObjectSerializer.

type ObjectSerializer

type ObjectSerializer interface {

	// Matches tests whether the given object may be serialized by the current
	// ObjectSerializer.
	//
	// If this method returns true, Serialize will be called on the object and no
	// further ObjectSerializers will be tested.
	Matches(object any) bool

	// Serialize serializes the given object into an io.Reader instance which will
	// be passed to the HTTP client caller.
	Serialize(object any) (io.Reader, error)

	// ContentType returns the content type of the serialized data that this
	// ObjectSerializer returns.
	ContentType() string
}

An ObjectSerializer is used to serialize response objects into a stream that may be passed to the HTTP client caller.

func NewDefaultJSONObjectSerializer

func NewDefaultJSONObjectSerializer() ObjectSerializer

NewDefaultJSONObjectSerializer returns an ObjectSerializer instance that will match ALL objects and attempt to serialize them as JSON.

func NewJSONObjectSerializer

func NewJSONObjectSerializer(fn MatcherFn) ObjectSerializer

NewJSONObjectSerializer returns an ObjectSerializer instance that will match only the objects that the given MatcherFn instance returns true for, and will attempt to serialize them as JSON.

type Request

type Request interface {

	// Raw returns the underling http.Request struct pointer.
	Raw() *http.Request

	// Method returns the HTTP request method used.
	Method() string

	// AdditionalContext returns the RequestContext object attached to this
	// request.
	//
	// Additional context may be used to store arbitrary data along with the
	// incoming request.
	AdditionalContext() RequestContext

	// GetHeader returns the first value associated with the given header name.
	//
	// If no such header was found on the request, the returned string will be
	// empty.
	//
	// This lookup is case-insensitive.
	GetHeader(header string) string

	// GetHeaders returns all the values associated with the given header name.
	//
	// If no such header was found on the request, the returned slice will be
	// empty.
	//
	// This lookup is case-insensitive.
	GetHeaders(header string) []string

	// HasQueryParam tests whether this request was sent with the target query
	// param as part of the URL.
	HasQueryParam(name string) bool

	// GetQueryParam fetches the value for the target query param from the request
	// URL.
	//
	// If the request URL did not contain the target query param, the returned
	// string will be empty.
	GetQueryParam(name string) string

	// GetCookie returns the cookie with the given name.
	//
	// If no such cookie was found, the return value will be nil.
	GetCookie(name string) *http.Cookie

	// HasCookie tests whether this request has the target cookie.
	HasCookie(name string) bool

	// GetCookies returns a slice of all the cookies sent with the request.
	GetCookies() []*http.Cookie

	// URIParam fetches the value of the URI param with the given name.
	//
	// URI params are the parameterized portion of a path set on the parent
	// controller.
	URIParam(name string) string

	// URIParams returns
	URIParams() map[string]string

	// Body returns an io.ReadCloser over the raw request body.
	Body() io.ReadCloser

	// WithBody executes the given function, passing in the request body.
	//
	// The request body will be automatically closed on return of the given
	// function.
	WithBody(fn func(reader io.Reader))

	// MultipartReader returns a MIME multipart reader if this is a
	// multipart/form-data or a multipart/mixed POST request, else returns nil and
	// an error.
	MultipartReader() (*multipart.Reader, error)
}

Request represents an incoming HTTP request.

func WrapRequest

func WrapRequest(r *http.Request) Request

WrapRequest wraps the given http.Request pointer in a new Request instance.

The new Request will have an empty RequestContext attached.

type RequestContext

type RequestContext interface {

	// Has tests whether the RequestContext contains and entry with the given key.
	Has(key string) bool

	// Get returns the value stored at the given key.
	Get(key string) any

	// Put sets the given value into the RequestContext at the given key.
	Put(key string, val any)

	// Len returns the current size of the RequestContext instance.
	Len() int

	// IsEmpty tests whether this RequestContext has a length of 0.
	IsEmpty() bool
}

RequestContext is a map of arbitrary state that may be attached to a Request instance as it passes through the various stages of the request handling process.

type RequestFilter

type RequestFilter interface {

	// FilterRequest may apply changes to the incoming Request's RequestContext,
	// or optionally, halt processing of the Request by returning a non-nil
	// Response.
	//
	// If this method returns a non-nil response, no further RequestFilters will
	// be called, and the RequestHandler will not be reached.  Instead, the Server
	// will return the response provided by this method.
	//
	// If this method returns a nil value, the request will be passed to the next
	// RequestFilter instance registered to either the server or the controller.
	FilterRequest(request Request) Response
}

A RequestFilter is a filter that is applied to incoming HTTP requests that may modify the RequestContext, or halt processing of the request by returning a non-nil Response.

RequestFilters are applied in the order that they are registered with global RequestFilters, i.e. ones set on the Server instance, applied before controller-specific RequestFilters.

type RequestFilterFunc

type RequestFilterFunc func(request Request) Response

RequestFilterFunc defines a function that implements the RequestFilter interface.

func (RequestFilterFunc) FilterRequest

func (r RequestFilterFunc) FilterRequest(request Request) Response

type RequestHandler

type RequestHandler interface {

	// HandleRequest is called to process incoming requests and transform them
	// into Response objects to be returned the HTTP client caller.
	HandleRequest(request Request) Response
}

RequestHandler represents the core part of a controller that actually processes a request.

type RequestHandlerFunc

type RequestHandlerFunc func(request Request) Response

A RequestHandlerFunc is a function that implements the RequestHandler interface.

func (RequestHandlerFunc) HandleRequest

func (r RequestHandlerFunc) HandleRequest(request Request) Response

type Response

type Response interface {

	// GetCode returns the HTTP status code set on this Response instance.
	//
	// If unset, the Response status code defaults to 200.
	GetCode() int

	// WithCode sets the HTTP status code of the response to the given value.
	//
	// If unset, the Response status code defaults to 200.
	WithCode(code int) Response

	// GetBody returns the body for this Response.
	GetBody() any

	// WithBody sets the body on this Response instance.
	//
	// The body may be any object and, if not an io.Reader, will be passed to the
	// first matching ObjectSerializer registered with the Server.
	//
	// If the body is an io.ReadCloser, the body will be closed automatically by
	// the server after the response has been written to the client.
	WithBody(body any) Response

	// GetHeaders returns the ResponseHeaders attached to this Response instance.
	GetHeaders() ResponseHeaders

	// WithHeader sets the target response header to the given values.
	WithHeader(header, value string, values ...string) Response

	// OnComplete sets a callback function that will be called after the request
	// processing is complete and the response has been sent to the HTTP client.
	OnComplete(fn func()) Response

	// GetOnComplete returns the OnComplete function, if one is present.
	GetOnComplete() func()
}

A Response builds the HTTP response that will be sent to the HTTP client that made the source request.

func NewResponse

func NewResponse() Response

NewResponse creates a new Response instance.

The created response will have no body or headers, and will default to a status code of 200.

type ResponseFilter

type ResponseFilter interface {

	// FilterResponse may apply changes to, or replace entirely, the passed
	// Response instance.
	//
	// FilterResponse is expected to always return a response instance.  If it
	// returns nil, the Server will respond with a 500 error.
	FilterResponse(request Request, response Response) Response
}

A ResponseFilter is a filter that is applied to outgoing HTTP responses that may modify or replace the Response.

ResponseFilters are applied in the order that they are registered, with global ResponseFilters, i.e. the ones set on the Server instance, being applied after the controller-specific ResponseFilters.

All ResponseFilter instances will be called regardless of what they return.

type ResponseFilterFunc added in v1.1.0

type ResponseFilterFunc func(request Request, response Response) Response

A ResponseFilterFunc is a function that implements the ResponseFilter interface.

func (ResponseFilterFunc) FilterResponse added in v1.1.0

func (r ResponseFilterFunc) FilterResponse(request Request, response Response) Response

type ResponseHeaders

type ResponseHeaders interface {
	// Set puts the given header value(s) into the header mapping, replacing any
	// value previously set for the target header.
	Set(header, value string, values ...string)

	// Append puts the given header value(s) into the header mapping, appending
	// to any value(s) previously set for the target header.
	Append(header, value string, values ...string)

	// GetFirst returns the first value set for the target header.
	GetFirst(header string) (value string, found bool)

	// GetAll returns all values set for the target header.
	GetAll(header string) (values []string, found bool)

	// GetNth returns the nth value set for the target header.
	GetNth(header string, n int) (value string, found bool)

	// ForEach iterates over all the set headers and calls the given function on
	// each.
	ForEach(fn func(header string, values []string))
}

ResponseHeaders is a mapping of header values that will be sent out with an HTTP response.

type Server

type Server interface {
	// WithLogger configures the server to use the given logrus logger instance
	// for internal server logging.
	//
	// This will overwrite any value previously set using WithLogger or
	// WithLoggerEntry.
	//
	// Passing nil will cause the server to panic with a nil pointer exception on
	// startup.
	WithLogger(logger *logrus.Logger) Server

	// WithLoggerEntry configures the server to use the given logrus logger entry
	// instance for internal server logging.
	//
	// This will overwrite any value previously set using WithLogger or
	// WithLoggerEntry.
	//
	// Passing nil will cause the server to panic with a nil pointer exception on
	// startup.
	WithLoggerEntry(logger *logrus.Entry) Server

	// WithReadTimeout sets the server's read timeout value to the given duration.
	//
	// If unset, the Server will default to a 30-second timeout.
	WithReadTimeout(timeout time.Duration) Server

	// WithWriteTimeout sets the server's write timeout value to the given
	// duration.
	//
	// If unset, the Server will default to a 30-second timeout.
	WithWriteTimeout(timeout time.Duration) Server

	// WithControllers adds the given ControllerSpec to the Server.
	//
	// When the Server is started, this ControllerSpec will be built into a
	// controller instance that will handle incoming HTTP requests that match the
	// target path and filters.
	WithControllers(controller ControllerSpec) Server

	// WithRequestFilters appends global RequestFilter instances that will be hit
	// for requests to any controller registered with the Server instance.
	//
	// Global RequestFilter instances are applied before controller specific
	// RequestFilter instances.
	WithRequestFilters(filters ...RequestFilter) Server

	// WithResponseFilters appends global ResponseFilter instances that will be
	// hit for outgoing responses from any controller registered with the Server
	// instance.
	//
	// Global ResponseFilter instances are applied after controller specific
	// ResponseFilter instances.
	WithResponseFilters(filters ...ResponseFilter) Server

	// WithObjectSerializers appends ObjectSerializer instances to the Server.
	//
	// ObjectSerializers are used to serialize non-stream objects into values that
	// may be streamed out to the requesting client.
	//
	// If no ObjectSerializer instances are provided, the default ObjectSerializer
	// will be used.  The default ObjectSerializer simply stringifies the object.
	//
	// ObjectSerializers are not applied to Response bodies of type io.Reader.
	//
	// ObjectSerializers will be tested in the order they are appended to the
	// server.  The first matching serializer will be used to serialize a Response
	// body.
	WithObjectSerializers(serializers ...ObjectSerializer) Server

	// With404Controller configures the Server's 404 Not Found controller, that
	// is, the controller that will be called when a client makes a request to an
	// endpoint that is not registered to the Server.
	//
	// Optionally requests to this controller may choose to use the global
	// RequestFilter and ResponseFilter instances like a normal controller.
	With404Controller(useGlobalFilters bool, controller ErrorControllerSpec) Server

	// With405Controller configures the Server's 405 Method Not Allowed
	// controller, that is, the controller that will be called with a client makes
	// a request to an endpoint using an HTTP method that is not supported by that
	// endpoint.
	//
	// Optionally requests to this controller may choose to use the global
	// RequestFilter and ResponseFilter instances like a normal controller.
	With405Controller(useGlobalFilters bool, controller ErrorControllerSpec) Server

	// Start starts the server, binding to the configured port and address,
	// optionally using a given router.
	//
	// If the router parameter is nil, a new router will be initialized for the
	// server.
	//
	// Once a server has started, no new filters, controllers, or serializers may
	// be registered.
	//
	// A server may only be started once.
	//
	// Example: No Router
	//   server := xhttp.NewServer(address, port)
	//   ...
	//   server.Start(nil)
	//
	// Example: With Router
	//
	//   router := mux.NewRouter()
	//   server := xhttp.NewServer(address, port)
	//   ...
	//   server.Start(router)
	Start(router *mux.Router)
}

A Server serves HTTP requests.

func NewServer

func NewServer(host string, port uint16) Server

Jump to

Keyboard shortcuts

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