Documentation ¶
Overview ¶
Package boar provides HTTP middleware for semantic and organized HTTP server applications
Index ¶
- Variables
- func NewHTTPErrorStatus(status int) error
- type BufferedResponseWriter
- func (w *BufferedResponseWriter) Close() error
- func (w *BufferedResponseWriter) Flush() (err error)
- func (w *BufferedResponseWriter) Header() http.Header
- func (w *BufferedResponseWriter) Len() int
- func (w *BufferedResponseWriter) Status() int
- func (w *BufferedResponseWriter) Write(b []byte) (n int, err error)
- func (w *BufferedResponseWriter) WriteHeader(status int)
- type Context
- type ErrorHandlerFunc
- type HTTPError
- type Handler
- type HandlerFunc
- type HandlerProviderFunc
- type JSON
- type Middleware
- type PanicError
- type ResponseWriter
- type Router
- func (rtr *Router) Delete(path string, h HandlerProviderFunc)
- func (rtr *Router) Get(path string, h HandlerProviderFunc)
- func (rtr *Router) Head(path string, h HandlerProviderFunc)
- func (rtr *Router) Method(method string, path string, createHandler HandlerProviderFunc)
- func (rtr *Router) MethodFunc(method string, path string, h HandlerFunc)
- func (rtr *Router) Options(path string, h HandlerProviderFunc)
- func (rtr *Router) Patch(path string, h HandlerProviderFunc)
- func (rtr *Router) Post(path string, h HandlerProviderFunc)
- func (rtr *Router) Put(path string, h HandlerProviderFunc)
- func (rtr *Router) RealRouter() *httprouter.Router
- func (rtr *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (rtr *Router) Trace(path string, h HandlerProviderFunc)
- func (rtr *Router) Use(mw ...Middleware)
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
var ( NewHTTPErrorStatus(http.StatusUnauthorized) // ErrForbidden is an HTTPError for StatusForbidden ErrForbidden = NewHTTPErrorStatus(http.StatusForbidden) // ErrNotFound is an HTTPError for StatusNotFound ErrNotFound = NewHTTPErrorStatus(http.StatusNotFound) // ErrNotAcceptable is an HTTPError for StatusNotAcceptable ErrNotAcceptable = NewHTTPErrorStatus(http.StatusNotAcceptable) // ErrUnsupportedMediaType is an HTTPError for StatusUnsupportedMediaType ErrUnsupportedMediaType = NewHTTPErrorStatus(http.StatusUnsupportedMediaType) // ErrGone is an HTTPError for StatusGone ErrGone = NewHTTPErrorStatus(http.StatusGone) // ErrTooManyRequests is an HTTPError for StatusTooManyRequests ErrTooManyRequests = NewHTTPErrorStatus(http.StatusTooManyRequests) // ErrEntityNotFound should be used to provide a more valuable 404 error // message to the client. Simply sending 404 with no body to the client // is confusing because it is not clear what was not found. Was the path // incorrect or was there simply no item in the datastore? ErrEntityNotFound // provides a distinction when URLs are currect, but there is simply // no record in the datastore ErrEntityNotFound = NewHTTPError(http.StatusNotFound, fmt.Errorf("entity not found")) )ErrUnauthorized =
var ( // MultiPartFormMaxMemory says how much memory to send to (*http.Request).ParseMultipartForm // Default is 2MB MultiPartFormMaxMemory = int64(1 << 20) // 2MB )
Functions ¶
func NewHTTPErrorStatus ¶
NewHTTPErrorStatus creates a new HTTP Error with the given status code and uses the default status text for that status code. These are useful for concise errors such as "Forbidden" or "Unauthorized"
Types ¶
type BufferedResponseWriter ¶
type BufferedResponseWriter struct {
// contains filtered or unexported fields
}
BufferedResponseWriter is an http.ResponseWriter that captures the status code and body written for retrieval after the response has been sent
func NewBufferedResponseWriter ¶
func NewBufferedResponseWriter(base http.ResponseWriter) *BufferedResponseWriter
NewBufferedResponseWriter creates a new BufferedResponseWriter
func (*BufferedResponseWriter) Close ¶
func (w *BufferedResponseWriter) Close() error
Close flushes the response stream and closes the writer. Subsequent calls to Body(), Len(), etc will yield no results
func (*BufferedResponseWriter) Flush ¶
func (w *BufferedResponseWriter) Flush() (err error)
Flush flushes the buffer into the write stream and sends the body to the client Once flush has been called, there can be no more headers or anything sent to the client
Flush is called internally by the Router once all middlewares, handlers, and error handlers have completely executed. This allows the middlewares access to writing headers, reading contents, etc.
func (*BufferedResponseWriter) Header ¶
func (w *BufferedResponseWriter) Header() http.Header
Header returns the header map that will be sent by WriteHeader. The Header map also is the mechanism with which Handlers can set HTTP trailers.
Unlike the default http.ResponseWriter, headers can be written *after* the response body has been written because the response body is buffered and therefore not written to the stream until Flush or Close is called
func (*BufferedResponseWriter) Len ¶
func (w *BufferedResponseWriter) Len() int
Len returns the amount of bytes that have been written so far
func (*BufferedResponseWriter) Status ¶
func (w *BufferedResponseWriter) Status() int
Status returns the currently set HTTP status code
func (*BufferedResponseWriter) Write ¶
func (w *BufferedResponseWriter) Write(b []byte) (n int, err error)
Write writes the data to the connection as part of an HTTP reply.
func (*BufferedResponseWriter) WriteHeader ¶
func (w *BufferedResponseWriter) WriteHeader(status int)
WriteHeader sets the http status code. Unlike the default http.ResponseWriter, this does _not_ begin the response transaction. This will simply store the status code until Flush is executed
type Context ¶
type Context interface { // Context is a shortcut for Request().Context() Context() context.Context // Request returns the underlying http.Request Request() *http.Request // Response returns the underlying http.ResponseWriter Response() ResponseWriter // ReadQuery parses the query string from the request into a struct // if the query string has invalid types (e.g. alpha for an int field) // then a ValidationError will be returned with a status code of 400 ReadQuery(v interface{}) error // ReadForm(v interface{}) error ReadJSON(v interface{}) error // ReadForm reads the contents of the request form and populates the values of v. ReadForm(v interface{}) error // WriteJSON writes the status code and then sends a json response message WriteJSON(status int, v interface{}) error // WriteStatus is an alias to c.Response().WriteHeader(status) WriteStatus(status int) error // URLParams returns all params as a key/value pair for quick lookups URLParams() httprouter.Params // ReadURLParams maps all URL parameters to struct fields of v and returns // a validation error if there are any type mismatches ReadURLParams(v interface{}) error }
Context is an http handler context
func NewContext ¶
func NewContext(r *http.Request, w http.ResponseWriter, ps httprouter.Params) Context
NewContext creates a new Context based on the rquest and response writer given
type ErrorHandlerFunc ¶
ErrorHandlerFunc is a func that handles errors returned by middlewares or handlers
type HTTPError ¶
HTTPError is an error that is communicated
func NewHTTPError ¶
NewHTTPError creates a new HTTPError that will be marshaled to the requestor
type HandlerFunc ¶
HandlerFunc is a function that handles an HTTP request
type HandlerProviderFunc ¶
HandlerProviderFunc is a prerequesite function that is used to generate handlers this is valuable to use like a factory
type Middleware ¶
type Middleware func(HandlerFunc) HandlerFunc
Middleware is a global middleware function
var PanicMiddleware Middleware = func(next HandlerFunc) HandlerFunc { return func(c Context) (err error) { defer func() { if r := recover(); r != nil { err = NewPanicError(r, debug.Stack()) } }() err = next(c) return } }
PanicMiddleware recovers from panics happening in http handlers and returns the error to be received by the normal middleware chain
type PanicError ¶
type PanicError struct { Stack []byte // contains filtered or unexported fields }
PanicError is an error caused by panic that was recovered
func NewPanicError ¶
func NewPanicError(recovered interface{}, stack []byte) *PanicError
NewPanicError creates a new PanicError with the callstack provided. You can get the current callstack with debug.Stack()
func (*PanicError) Cause ¶
func (p *PanicError) Cause() error
func (*PanicError) Error ¶
func (p *PanicError) Error() string
func (*PanicError) MarshalJSON ¶
func (p *PanicError) MarshalJSON() ([]byte, error)
func (*PanicError) Status ¶
func (p *PanicError) Status() int
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter io.Closer Flush() error Status() int Len() int }
ResponseWriter is an http.ResponseWriter that captures the status code and body written for retrieval after the response has been sent
type Router ¶
type Router struct { // ErrorHandler is a middleware that handles writing errors back to the client when an error // an error occurs in the handler. It is the first middleware executed therefore It should // always return the error that it handled ErrorHandler ErrorHandlerFunc // contains filtered or unexported fields }
Router is an http router
func NewRouterWithBase ¶
func NewRouterWithBase(r *httprouter.Router) *Router
NewRouterWithBase allows you to create a new http router with the provided
httprouter.Router instead of the default httprouter.New()
func (*Router) Delete ¶
func (rtr *Router) Delete(path string, h HandlerProviderFunc)
Delete is a handler that accepts only DELETE requests
func (*Router) Get ¶
func (rtr *Router) Get(path string, h HandlerProviderFunc)
Get is a handler that accepts only GET requests
func (*Router) Head ¶
func (rtr *Router) Head(path string, h HandlerProviderFunc)
Head is a handler that acceps HEAD requests
func (*Router) Method ¶
func (rtr *Router) Method(method string, path string, createHandler HandlerProviderFunc)
Method is a path handler that uses a factory to generate the handler this is particularly useful for filling contextual information into a struct before passing it along to handle the request
func (*Router) MethodFunc ¶
func (rtr *Router) MethodFunc(method string, path string, h HandlerFunc)
MethodFunc sets a HandlerFunc for a url with the given method. It is used for simple handlers that do not require any building. This is not a recommended for common use cases
func (*Router) Options ¶
func (rtr *Router) Options(path string, h HandlerProviderFunc)
Options is a handler that accepts only OPTIONS requests It is not recommended to use this as the router automatically handles OPTIONS requests by default
func (*Router) Patch ¶
func (rtr *Router) Patch(path string, h HandlerProviderFunc)
Patch is a handler that accepts only PATCH requests
func (*Router) Post ¶
func (rtr *Router) Post(path string, h HandlerProviderFunc)
Post is a handler that accepts only POST requests
func (*Router) Put ¶
func (rtr *Router) Put(path string, h HandlerProviderFunc)
Put is a handler that accepts only PUT requests
func (*Router) RealRouter ¶
func (rtr *Router) RealRouter() *httprouter.Router
RealRouter returns the httprouter.Router used for actual serving
func (*Router) Trace ¶
func (rtr *Router) Trace(path string, h HandlerProviderFunc)
Trace is a handler that accepts only TRACE requests
func (*Router) Use ¶
func (rtr *Router) Use(mw ...Middleware)
Use injects a middleware into the http requests. They are executed in the order in which they are added.
type ValidationError ¶
type ValidationError struct { Errors []error // contains filtered or unexported fields }
ValidationError is an HTTPError that was caused by validation. Validation errors are typically caused by valid tags or improper type mapping between input types and struct fields. These should always be considered 400 errors. This is useful when you want to control the flow of validation errors within your handlers.
Example:
func Handle(c Context) error { err := c.ReadJSON(&req) if err != nil { if ok, verr := err.(*ValidationError); ok { return c.WriteJSON(http.StatusBadRequest, map[string]interface{}{ "validationErrors": err.Error(), }) } return err } }
func NewValidationError ¶
func NewValidationError(fieldName string, err error) *ValidationError
NewValidationError creates a new Validation error with a single reason. fieldName is the area where the validation failed bodyField, or urlParamsField
func NewValidationErrors ¶
func NewValidationErrors(fieldName string, errs []error) *ValidationError
NewValidationErrors creates a new Validation error with reasons. fieldName is the area where the validation failed bodyField, or urlParamsField
func (*ValidationError) Cause ¶
func (e *ValidationError) Cause() error
Cause is the underlying cause(s) of the validation error
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
func (*ValidationError) MarshalJSON ¶
func (e *ValidationError) MarshalJSON() ([]byte, error)
MarshalJSON allows overrides json.Marshal default behavior
func (*ValidationError) Status ¶
func (e *ValidationError) Status() int
Status is the http status to be used for responding to the client