Documentation ¶
Overview ¶
Package ale provides some utilites to extend standard HTTP handlers for easier error handling.
The core of this package is the ErrorHandler and ErrorHandlerFunc types, which simply extends their standard library companion types (http.Handler and http.HandlerFunc respectively) to return errors.
Such a handler (or middleware) should either write a response to the standard http.ResponseWriter _or_ return an error. Any such errors are converted to a response by an ErrorReporter. This allows putting all error-handling logic in a single location, rather than scattered throughout your application.
Index ¶
- Variables
- func BasicReporter(w http.ResponseWriter, r *http.Request, err error)
- func ConvertMiddleware(emw Middleware) func(http.Handler) http.Handler
- func ErrorForwarder(handler Handler) http.Handlerdeprecated
- func ErrorForwarderFunc(handler HandlerFunc) http.Handlerdeprecated
- func HandleErrors(report ErrorReporter) func(http.Handler) http.Handler
- func IsUsed(w http.ResponseWriter) (bool, error)
- func Recover() func(Handler) Handler
- func RequestLogger(cb func(*LogContext)) func(Handler) Handler
- func ServeJSON(w http.ResponseWriter, i interface{}, status ...int) error
- func Std(h Handler) http.Handler
- func StdRecover() func(http.Handler) http.Handler
- func StdRequestLogger(cb func(*LogContext)) func(http.Handler) http.Handler
- func StdTrackWriterUsage(next http.Handler) http.Handler
- type Chain
- type ErrorHandlerdeprecated
- type ErrorHandlerFuncdeprecated
- type ErrorMiddlewaredeprecated
- type ErrorReporter
- type Handler
- type HandlerFunc
- type LogContext
- type Middleware
- type UsedWriter
Constants ¶
This section is empty.
Variables ¶
var DefaultReporter = BasicReporter
DefaultReporter is used by Std() any time an error has not been injected with HandleErrors.
Functions ¶
func BasicReporter ¶ added in v0.15.0
func BasicReporter(w http.ResponseWriter, r *http.Request, err error)
BasicReporter is a bare ErrorReporter, which wraps http.Error. If err satisfies the interface{ HTTPStatus() int } interface, the method is called to determine the HTTP status.
If w is a UsedWriter, and returns true, then nothing is written to the response.
func ConvertMiddleware ¶ added in v0.13.0
func ConvertMiddleware(emw Middleware) func(http.Handler) http.Handler
ConvertMiddleware converts ale middleware to standard middleware. See Std() to understand how errors are handled.
func ErrorForwarder
deprecated
added in
v0.12.0
func ErrorForwarderFunc
deprecated
added in
v0.12.0
func ErrorForwarderFunc(handler HandlerFunc) http.Handler
ErrorForwarderFunc works like ErrorForwarder, but accepts a raw function.
Deprecated: HandlerFunc now supports ServeHTTP directly.
func HandleErrors ¶ added in v0.12.0
func HandleErrors(report ErrorReporter) func(http.Handler) http.Handler
HandleErrors should be called at the top of your middleware chain, likely as the very first middleware, even before any panic recovery. It injects a pointer to an error in the context of the request, to abuse the context for out-of-band error passing. Evil, I know. This allows you to mix standard HTTP handlers or middlewares with the error-aware versions in this package. If any middleware/handler returns an error, report is called.
func IsUsed ¶ added in v0.17.0
func IsUsed(w http.ResponseWriter) (bool, error)
WriterIsDIsUsedone returns true if a response has been written. An error is returned if the underlying writer is not a DoneWriter.
func Recover ¶ added in v0.13.0
Recover converts any panic into an error. Requires use of HandleErrors.
func RequestLogger ¶ added in v0.13.0
func RequestLogger(cb func(*LogContext)) func(Handler) Handler
RequestLogger gathers request statistics for logging, and calls cb to do the actual logging. Any error will be included in the logging context, and consumed. This handler always returns a nil error.
func ServeJSON ¶
func ServeJSON(w http.ResponseWriter, i interface{}, status ...int) error
ServeJSON marshals i and serves it on w. If the Content-Type header is not yet set on w, it will be set to "application/json; charset=utf-8". If status is passed, the first status value will be passed to w.WriteHeader, otherwise the default of http.StatusOK is used.
func Std ¶ added in v0.14.0
Std converts h into a standard http.Handler. If h returns an error:
- If possible, the error is injected to the context (when HandleErrors has been called).
- Otherwise, DefaultReporter is called
func StdRecover ¶ added in v0.13.0
StdRecover works as Recover, but with standard middleware signatures.
func StdRequestLogger ¶ added in v0.14.0
func StdRequestLogger(cb func(*LogContext)) func(http.Handler) http.Handler
StdRequestLogger gathers request statistics for logging, and calls cb to do the actual logging. If HandleErrors was called first, any error will be included in the logging context.
Types ¶
type Chain ¶ added in v0.16.0
type Chain struct {
// contains filtered or unexported fields
}
Chain represents a complete middleware chain and adapter.
func (*Chain) Handler ¶ added in v0.16.0
Handler applies the middleware chain to h. This method injects an error by calling HandleErrors.
func (*Chain) SetErrorReporter ¶ added in v0.16.0
func (c *Chain) SetErrorReporter(r ErrorReporter)
SetErrerReporter sets the ErrorReporter, to handle any errors generated by a request. If unset, BasicReporter is used.
func (*Chain) SetLogger ¶ added in v0.16.0
func (c *Chain) SetLogger(l func(*LogContext))
SetLogger sets a request logger. If unset, requests are not logged by ale.
func (*Chain) Use ¶ added in v0.16.0
func (m *Chain) Use(mw Middleware)
Use adds mw to the end of the middleware chain.
type ErrorHandler
deprecated
added in
v0.12.0
type ErrorHandlerFunc
deprecated
type ErrorHandlerFunc = HandlerFunc
ErrorHandlerFunc is an alias to HandlerFunc.
Deprecated: Use HandlerFunc
type ErrorMiddleware
deprecated
added in
v0.12.0
type ErrorMiddleware = Middleware
ErrorMiddleware is an alias to Middleware.
Deprecated: Use Middleware
type ErrorReporter ¶
type ErrorReporter func(w http.ResponseWriter, r *http.Request, err error)
ErrorReporter is a function that can report an HTTP error returned by a ErrorHandlerFunc.
func (ErrorReporter) HTTPHandlerFunc ¶
func (c ErrorReporter) HTTPHandlerFunc(f HandlerFunc) http.HandlerFunc
HTTPHandlerFunc wraps a HandlerFunc, such that it can be used as a standard http.HandlerFunc.
type Handler ¶ added in v0.14.0
type Handler interface { // ServeHTTPE serves the same purpose as http.Handler's ServeHTTP, except // that it may return an error. The function should _either_ write to // http.ResponseWriter _or_ return an error. ServeHTTPE(http.ResponseWriter, *http.Request) error }
Handler extends http.Handler with an error return value.
func TrackWriterUsage ¶ added in v0.17.0
TrackWriterUsage is an ale middleware which wraps the standard http.ResponseWriter with a DoneWriter. Subsequent middlewares or handlers should use the WriterIsDone method to check the status.
type HandlerFunc ¶ added in v0.14.0
type HandlerFunc func(http.ResponseWriter, *http.Request) error
HandlerFunc extends the standard http.HandlerFunc to support error handling more easily.
HandlerFunc also satisfies the http.Handler interface by implementing the ServeHTTP() method. See the docs for Std() for how errors are handled.
func (HandlerFunc) ServeHTTP ¶ added in v0.14.0
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (HandlerFunc) ServeHTTPE ¶ added in v0.14.0
func (f HandlerFunc) ServeHTTPE(w http.ResponseWriter, r *http.Request) error
type LogContext ¶
type LogContext struct { // Request contains a shallow copy of the original request, without the // body. Request *http.Request // StatusCode is the HTTP status code sent to the client. StatusCode int // ResponseHeader is the list of header values sent to the client. ResponseHeader http.Header // ResponseHeader is the list of trailer values sent to the client. ResponseTrailer http.Header // ResponseBytes is the number of bytes written in the response body. ResponseBytes int64 // RequestBytes is the number of bytes read from the request body. This // can differ from the Content-Length value if reading is not completed, or // in case Content-Length is unset. RequestBytes int64 // StartTime is the time the request was received by the server StartTime time.Time // ElapsedTime is the duration it took to serve the request ElapsedTime time.Duration // Error is the error, if any, returned from the handler/middlware chain. Error error // contains filtered or unexported fields }
LogContext captures data about a request and response, for logging.
func NewLogContext ¶
func NewLogContext(w http.ResponseWriter, r *http.Request) *LogContext
NewLogContext returns a new log context, which should be used as a ResponseWriter for subsequent handlers in middleware.
Example:
func LogMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { logCtx := NewLogContext(w,r) next.ServeHTTP(logCtx, r) logCtx.Finalize() // Log logCtx here }) }
func (*LogContext) Finalize ¶
func (l *LogContext) Finalize()
Finalize should be called after ServeHTTP, to finalize the response values. Without this call, trailers will not be set, and elapsed time is not calculated.
func (*LogContext) Header ¶
func (l *LogContext) Header() http.Header
Header returns the header map that will be sent by WriteHeader.
func (*LogContext) Write ¶
func (l *LogContext) Write(p []byte) (int, error)
Write writes the data to the connection as part of an HTTP reply.
func (*LogContext) WriteHeader ¶
func (l *LogContext) WriteHeader(status int)
WriteHeader sends an HTTP response header with the provided status code.
type Middleware ¶ added in v0.14.0
Middleware extends the standard middleware with error handling.
type UsedWriter ¶ added in v0.17.0
type UsedWriter interface { http.ResponseWriter Used() bool }
UsedWriter extends the http.ResponseWriter interface to return a bool to indicate whether anything has been written.
To use it, call the TrackWriterUsage middleware early in your middleware stack. Then in other middlewares or handlers, you can use the WasUsed method to check the status.
func main() { r := chi.NewRouter() r.Use(ale.TrackWriterUsage) // and other middlewares r.Get("/", func(w http.ResponseWriter, r *http.Request) { if done, _ := ale.WasUsed(w); done { // Nothing to do, a response was already sent return } // Normal operation here... }) }
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package donewriter provides a simple wrapper around an http.ResponseWriter to track when a response has been sent.
|
Package donewriter provides a simple wrapper around an http.ResponseWriter to track when a response has been sent. |
Package envconf provides simple functionality for reading configuration from the environment, such as for use within a 12-Factor Application.
|
Package envconf provides simple functionality for reading configuration from the environment, such as for use within a 12-Factor Application. |
Package errors is a drop-in replacement for the errors package in the standard library, with extensions useful for developing web applications.
|
Package errors is a drop-in replacement for the errors package in the standard library, with extensions useful for developing web applications. |
Package httperr provides HTTP-centric extensions to standard errors.
|
Package httperr provides HTTP-centric extensions to standard errors. |
Package panicerr makes it easy to recover panics, and convert them to standard errors.
|
Package panicerr makes it easy to recover panics, and convert them to standard errors. |
Package view provides an HTTP middleware to provide a simple View, based on Go templates.
|
Package view provides an HTTP middleware to provide a simple View, based on Go templates. |