Categorygithub.com/bobg/mid
modulepackage
1.9.2
Repository: https://github.com/bobg/mid.git
Documentation: pkg.go.dev

# README

Mid - Assorted middleware for HTTP services.

Go Reference Go Report Card Tests Coverage Status

This is mid, a collection of useful middleware for HTTP services.

Err

The Err function turns a func(http.ResponseWriter, *http.Request) error into an http.Handler, allowing handler functions to return errors in a more natural fashion. These errors result in the handler producing an HTTP 500 status code, but CodeErr and Responder allow you to control this behavior (see below). A nil return produces a 200, or a 204 (“no content”) if no bytes were written to the response object.

Usage:

func main() {
  http.Handle("/foo", Err(fooHandler))
  http.ListenAndServe(":8080", nil)
}

func fooHandler(w http.ResponseWriter, req *http.Request) error {
  if x := req.FormValue("x"); x != "secret password" {
    return CodeErr{C: http.StatusUnauthorized}
  }
  fmt.Fprintf(w, "You know the secret password")
  return nil
}

JSON

The JSON function turns a func(context.Context, X) (Y, error) into an http.Handler, where X is the type of a parameter into which the HTTP request body is automatically JSON-unmarshaled, and Y is the type of a result that is automatically JSON-marshaled into the HTTP response. Any error is handled as with Err (see above). All parts of the func signature are optional: the context.Context parameter, the X parameter, the Y result, and the error result.

Usage:

func main() {
  // Parses the request body as a JSON-encoded array of strings,
  // then sorts, re-encodes, and returns that array.
  http.Handle("/bar", JSON(barHandler))

  http.ListenAndServe(":8080", nil)
}

func barHandler(inp []string) []string {
  sort.Strings(inp)
  return inp
}

CodeErr and Responder

CodeErr is an error type suitable for returning from Err- and JSON-wrapped handlers that can control the HTTP status code that gets returned. It contains an HTTP status code field and a nested error.

Responder is an interface (implemented by CodeErr) that allows an error type to control how Err- and JSON-wrapped handlers respond to the pending request.

ResponseWrapper

ResponseWrapper is an http.ResponseWriter that wraps a nested http.ResponseWriter and also records the status code and number of bytes sent in the response.

Trace

The Trace function wraps an http.Handler and decorates the context.Context in its *http.Request with any “trace ID” string found in the request header.

Log

The Log function wraps an http.Handler with a function that writes a simple log line on the way into and out of the handler. The log line includes any “trace ID” found in the request’s context.Context.

# Functions

ContextSession returns the [Session] associated with a context (by [SessionHandler]), if there is one.
CSRFCheck checks a CSRF token against a session for validity.
CSRFToken generates a new token containing a random nonce hashed with this session's CSRF key.
Err wraps an error-returning function as an [http.Handler].
Errf is a convenience wrapper for [http.Error].
GetSession checks for a session cookie in a given HTTP request and gets the corresponding session from the store.
IsNoSession tests whether the given error is either [ErrNoSession] or [http.ErrNoCookie].
JSON produces an [http.Handler] by JSON encoding and decoding of a given function's input and output.
Log adds logging on entry to and exit from an [http.Handler] using [log.Printf].
Request returns the pending *http.Request object when called on the context passed to a JSON handler.
RespondJSON responds to an http request with a JSON-encoded object.
ResponseWriter returns the pending http.ResponseWriter object when called on the context passed to a JSON handler.
SessionHandler is an [http.Handler] middleware wrapper.
Trace decorates a request's context with a trace ID.
TraceID returns the trace ID decorating the given context, if any.

# Variables

ErrCSRF is the error produced when an invalid CSRF token is presented to [CSRFCheck].
ErrNoSession is the error produced by [SessionStore.Get] when no matching session is found.

# Structs

CodeErr is an error that can be returned from the function wrapped by [Err] to control the HTTP status code returned from the pending request.
LimitedTransport is an [http.RoundTripper] that limits the rate of requests it makes using a [Limiter].
ResponseWrapper implements [http.ResponseWriter], delegating calls to a wrapped http.ResponseWriter object.

# Interfaces

Limiter is the type of an object that can be used to limit the rate of some operation.
Responder is an interface for objects that know how to respond to an HTTP request.
Session is the type of a session stored in a [SessionStore].
SessionStore is persistent storage for session objects.