Documentation
¶
Overview ¶
Package express is a fast, minimalist web framework for Go, modeled after the Node.js Express framework. It provides a familiar routing API, chainable request/response helpers, and middleware support on top of the standard library's net/http package.
A minimal application looks like this:
app := express.New()
app.Get("/", func(req *express.Request, res *express.Response, next express.Next) {
res.Send("Hello World")
})
log.Fatal(app.Listen(":3000"))
Index ¶
- Constants
- type Application
- func (app *Application) Disable(name string) *Application
- func (app *Application) Disabled(name string) bool
- func (app *Application) Enable(name string) *Application
- func (app *Application) Enabled(name string) bool
- func (app *Application) Engine(ext string, fn EngineFunc) *Application
- func (app *Application) GetSetting(name string) any
- func (app *Application) Listen(addr string) error
- func (app *Application) ListenWithServer(server *http.Server) error
- func (app *Application) Locals() map[string]any
- func (app *Application) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (app *Application) Set(name string, value any) *Application
- type CookieOptions
- type EngineFunc
- type ErrorHandler
- type Handler
- func JSON() Handler
- func Logger() Handler
- func Multipart(maxMemory int64) Handler
- func Recover() Handler
- func Session(opts ...SessionOptions) Handler
- func Static(root string) Handler
- func Text() Handler
- func URLEncoded() Handler
- func WrapHandler(h http.Handler) Handler
- func WrapHandlerFunc(fn func(http.ResponseWriter, *http.Request)) Handler
- type MemorySessionStore
- type Next
- type ParamHandler
- type Range
- type Request
- func (req *Request) Accepts(offers ...string) string
- func (req *Request) AcceptsCharsets(offers ...string) string
- func (req *Request) AcceptsEncodings(offers ...string) string
- func (req *Request) AcceptsLanguages(offers ...string) string
- func (req *Request) AllParams() map[string]string
- func (req *Request) Body() any
- func (req *Request) BodyJSON(dst any) error
- func (req *Request) Cookie(name string) string
- func (req *Request) Files(name string) []*multipart.FileHeader
- func (req *Request) Form() url.Values
- func (req *Request) FormFile(name string) (multipart.File, *multipart.FileHeader, error)
- func (req *Request) FormValue(name string) string
- func (req *Request) Fresh(res *Response) bool
- func (req *Request) Get(field string) string
- func (req *Request) Header(field string) string
- func (req *Request) Hostname() string
- func (req *Request) IP() string
- func (req *Request) Is(typ string) bool
- func (req *Request) Method() string
- func (req *Request) OriginalURL() string
- func (req *Request) Params(name string) string
- func (req *Request) Path() string
- func (req *Request) Protocol() string
- func (req *Request) Query(name string) string
- func (req *Request) QueryValues() url.Values
- func (req *Request) Ranges(size int64) ([]Range, bool)
- func (req *Request) Secure() bool
- func (req *Request) Session() *SessionData
- func (req *Request) Set(key string, value any)
- func (req *Request) SetBody(v any)
- func (req *Request) SetPath(p string)
- func (req *Request) Stale(res *Response) bool
- func (req *Request) Value(key string) (any, bool)
- type Response
- func (res *Response) Append(field, value string) *Response
- func (res *Response) Attachment(filename ...string) *Response
- func (res *Response) ClearCookie(name string) *Response
- func (res *Response) Cookie(name, value string, opts *CookieOptions) *Response
- func (res *Response) Download(path string, filename ...string) error
- func (res *Response) ETag(tag string) *Response
- func (res *Response) End()
- func (res *Response) Flush() bool
- func (res *Response) Format(handlers map[string]func())
- func (res *Response) Fresh() bool
- func (res *Response) GetHeader(field string) string
- func (res *Response) JSON(v any) *Response
- func (res *Response) LastModified(t time.Time) *Response
- func (res *Response) Location(url string) *Response
- func (res *Response) NotModified()
- func (res *Response) OnBeforeWrite(fn func())
- func (res *Response) Redirect(args ...any) *Response
- func (res *Response) Render(name string, data ...any) error
- func (res *Response) SSE() *SSEWriter
- func (res *Response) Send(body any) *Response
- func (res *Response) SendChunked(data []byte, chunkSize int) error
- func (res *Response) SendFile(path string) error
- func (res *Response) SendStatus(code int) *Response
- func (res *Response) SendStream(r io.Reader, chunkSize ...int) error
- func (res *Response) Set(field, value string) *Response
- func (res *Response) Status(code int) *Response
- func (res *Response) StatusCode() int
- func (res *Response) Stream(fn func(w io.Writer) error) error
- func (res *Response) Type(t string) *Response
- func (res *Response) Vary(field string) *Response
- func (res *Response) Write(p []byte) (int, error)
- func (res *Response) WriteChunk(p []byte) (int, error)
- func (res *Response) WriteString(s string) (int, error)
- func (res *Response) Written() bool
- type Route
- type RouteRegistrar
- type Router
- func (r *Router) All(path string, handlers ...Handler) *Router
- func (r *Router) Delete(path string, handlers ...Handler) *Router
- func (r *Router) Get(path string, handlers ...Handler) *Router
- func (r *Router) Head(path string, handlers ...Handler) *Router
- func (r *Router) Options(path string, handlers ...Handler) *Router
- func (r *Router) Param(name string, fn ParamHandler) *Router
- func (r *Router) Patch(path string, handlers ...Handler) *Router
- func (r *Router) Post(path string, handlers ...Handler) *Router
- func (r *Router) Put(path string, handlers ...Handler) *Router
- func (r *Router) Query(path string, handlers ...Handler) *Router
- func (r *Router) Route(path string) *Route
- func (r *Router) Use(args ...any) *Router
- type RouterOptions
- type SSEWriter
- type SessionData
- type SessionOptions
- type SessionStore
Constants ¶
const DefaultSessionCookie = "connect.sid"
DefaultSessionCookie is the cookie name used by the session middleware, matching the default used by Node's express-session.
const MethodQuery = "QUERY"
MethodQuery is the QUERY HTTP method token. It is not yet part of the standard library's net/http method constants, so it is defined here.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Application ¶
type Application struct {
*Router
// contains filtered or unexported fields
}
Application is the top-level express app. It embeds a Router so every routing method (Get, Post, Use, ...) is available directly on the app, and adds server lifecycle helpers such as Listen.
func (*Application) Disable ¶
func (app *Application) Disable(name string) *Application
Disable turns a boolean setting off.
func (*Application) Disabled ¶
func (app *Application) Disabled(name string) bool
Disabled reports whether a boolean setting is turned off.
func (*Application) Enable ¶
func (app *Application) Enable(name string) *Application
Enable turns a boolean setting on.
func (*Application) Enabled ¶
func (app *Application) Enabled(name string) bool
Enabled reports whether a boolean setting is turned on.
func (*Application) Engine ¶
func (app *Application) Engine(ext string, fn EngineFunc) *Application
Engine registers a template engine for a file extension (e.g. ".html", ".pug"). The extension should include the leading dot.
func (*Application) GetSetting ¶
func (app *Application) GetSetting(name string) any
GetSetting returns the value of a previously configured setting.
func (*Application) Listen ¶
func (app *Application) Listen(addr string) error
Listen binds and listens for connections on the given address, e.g. ":3000". It blocks until the server exits and returns any error from ListenAndServe.
func (*Application) ListenWithServer ¶
func (app *Application) ListenWithServer(server *http.Server) error
ListenWithServer lets callers supply a preconfigured *http.Server (for TLS, custom timeouts, etc.). The app is installed as the server's handler.
func (*Application) Locals ¶
func (app *Application) Locals() map[string]any
Locals returns the application-wide locals map.
func (*Application) ServeHTTP ¶
func (app *Application) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP makes Application satisfy http.Handler so it can be handed to any net/http server, httptest, or wrapped by other middleware.
func (*Application) Set ¶
func (app *Application) Set(name string, value any) *Application
Set assigns a setting name to a value, returning the app for chaining.
type CookieOptions ¶
type CookieOptions struct {
Path string
Domain string
MaxAge int
Secure bool
HTTPOnly bool
SameSite http.SameSite
}
CookieOptions configures a cookie set via res.Cookie.
type EngineFunc ¶
EngineFunc renders a template file at path with the given data and returns the rendered output. Register one with app.Engine to support a template language.
type ErrorHandler ¶
ErrorHandler is a handler that additionally receives an error. When a handler calls next(err), express skips ordinary handlers and invokes the next registered ErrorHandler.
type Handler ¶
Handler is the express request handler signature. Every handler receives the request, the response, and a Next function used to pass control to the next matching handler in the stack.
func JSON ¶
func JSON() Handler
JSON returns middleware that parses JSON request bodies into a map[string]any (or []any) and stores the result on req via SetBody. It only acts on requests whose Content-Type is JSON.
func Logger ¶
func Logger() Handler
Logger returns middleware that logs each request's method, path, status, and duration to the standard logger, in a concise Express/morgan-like format.
func Multipart ¶
Multipart returns middleware that parses multipart/form-data request bodies, making fields available via req.FormValue and files via req.FormFile. maxMemory bounds the in-memory buffer (0 uses the 32 MiB default).
func Recover ¶
func Recover() Handler
Recover returns middleware that recovers from panics in downstream handlers and converts them into a 500 response, keeping the server alive.
func Session ¶
func Session(opts ...SessionOptions) Handler
Session returns middleware that loads a per-request session from a cookie and persists changes automatically. Access it in handlers via req.Session().
func Static ¶
Static returns middleware that serves files from root. Requests that do not resolve to an existing file fall through to the next handler.
func Text ¶
func Text() Handler
Text returns middleware that reads a text/plain body into req.Body() as a string.
func URLEncoded ¶
func URLEncoded() Handler
URLEncoded returns middleware that parses application/x-www-form-urlencoded request bodies and stores them on req as url.Values.
func WrapHandler ¶
WrapHandler adapts a standard net/http handler into an express Handler so it can be mounted with app.Use, e.g. to attach a Socket.IO server:
app.Use("/socket.io", express.WrapHandler(io)) // io is an http.Handler
The wrapped handler receives the raw request (req.Raw) and response writer (res.Writer) — so it can hijack the connection for WebSocket upgrades — and is treated as terminal: express does not run later handlers for it.
func WrapHandlerFunc ¶
func WrapHandlerFunc(fn func(http.ResponseWriter, *http.Request)) Handler
WrapHandlerFunc is WrapHandler for an http.HandlerFunc.
type MemorySessionStore ¶
type MemorySessionStore struct {
// contains filtered or unexported fields
}
MemorySessionStore is an in-memory SessionStore for development and single-process use.
func NewMemorySessionStore ¶
func NewMemorySessionStore() *MemorySessionStore
NewMemorySessionStore creates an empty in-memory session store.
func (*MemorySessionStore) Destroy ¶
func (m *MemorySessionStore) Destroy(id string)
type Next ¶
type Next func(err ...error)
Next advances to the next handler. Calling it with no arguments continues the stack; calling it with a non-nil error jumps to error-handling middleware.
type ParamHandler ¶
ParamHandler processes a captured route parameter before the route's handlers run. It receives the parameter's value and, like any handler, must call next to continue (or next(err) to fail).
type Request ¶
type Request struct {
// Raw is the underlying standard-library request.
Raw *http.Request
// contains filtered or unexported fields
}
Request wraps an *http.Request and exposes Express-style accessors for route parameters, query values, headers, and the parsed request body.
func (*Request) Accepts ¶
Accepts returns the best match among the offered types for the request's Accept header, or "" when none is acceptable. Offers may be extensions ("html", "json") or full media types ("text/html"). With no offers it returns the client's most-preferred type.
func (*Request) AcceptsCharsets ¶
AcceptsCharsets returns the best match among the offered charsets for the Accept-Charset header, or "".
func (*Request) AcceptsEncodings ¶
AcceptsEncodings returns the best match among the offered encodings for the Accept-Encoding header, or "".
func (*Request) AcceptsLanguages ¶
AcceptsLanguages returns the best match among the offered languages for the Accept-Language header, or "".
func (*Request) Body ¶
Body returns the parsed request body. Call one of the Parse* helpers or the body-parser middleware first; otherwise it returns nil.
func (*Request) Files ¶
func (req *Request) Files(name string) []*multipart.FileHeader
Files returns all uploaded file headers for a form field.
func (*Request) FormFile ¶
FormFile returns the first uploaded file for the given form field, along with its multipart header. The multipart form must have been parsed first (via the Multipart middleware or by calling FormFile, which parses on demand).
func (*Request) Fresh ¶
Fresh reports whether the client's cached response is still fresh for this request, based on the response's ETag / Last-Modified headers and the request's If-None-Match / If-Modified-Since headers. When true, a handler may send 304 Not Modified instead of a body. Fresh only applies to GET and HEAD.
func (*Request) Hostname ¶
Hostname returns the host portion of the request, honoring the Host header.
func (*Request) Is ¶
Is reports whether the request's Content-Type matches the given type, e.g. req.Is("json") or req.Is("text/html").
func (*Request) OriginalURL ¶
OriginalURL returns the full request URI as received.
func (*Request) Protocol ¶
Protocol returns "https" when the request arrived over TLS, else "http".
func (*Request) QueryValues ¶
QueryValues returns the parsed query string as url.Values.
func (*Request) Ranges ¶
Ranges parses the request Range header against a resource of the given size, returning the satisfiable byte ranges. It returns (nil, false) when there is no Range header, and (nil, true) when the header is present but unsatisfiable.
func (*Request) Session ¶
func (req *Request) Session() *SessionData
Session returns the session attached to the request by the Session middleware, or nil if the middleware is not installed.
func (*Request) SetPath ¶
SetPath rewrites the request path and, crucially, the path used by the router to match routes. Middleware that rewrites URLs (rewrite, basepath, ...) must call SetPath rather than mutating req.Raw.URL.Path directly, so that route matching downstream sees the new path. It also updates req.Raw.URL.Path so handlers observe a consistent value.
type Response ¶
type Response struct {
// Writer is the underlying standard-library response writer.
Writer http.ResponseWriter
// Locals holds values scoped to this request/response cycle, mirroring
// Express's res.locals.
Locals map[string]any
// contains filtered or unexported fields
}
Response wraps an http.ResponseWriter and provides chainable Express-style helpers for setting status codes, headers, and writing bodies.
func (*Response) Attachment ¶
Attachment sets the Content-Disposition header to attachment. With a filename it also advertises the download name and sets a matching Content-Type.
func (*Response) ClearCookie ¶
ClearCookie expires a cookie on the client.
func (*Response) Cookie ¶
func (res *Response) Cookie(name, value string, opts *CookieOptions) *Response
Cookie sets a Set-Cookie header. opts may be nil for a session cookie.
func (*Response) Download ¶
Download sends the file at path as an attachment, prompting the browser to save it. When filename is empty the base name of path is used.
func (*Response) ETag ¶
ETag sets a (strong) ETag header from an already-computed tag. The value is quoted if not already.
func (*Response) End ¶
func (res *Response) End()
End finalizes the response with no (further) body.
func (*Response) Flush ¶
Flush sends any buffered response data to the client immediately, if the underlying writer supports flushing. It commits the headers first. Returns true when a flush actually occurred.
func (*Response) Format ¶
Format performs content negotiation, invoking the handler for the best type the client accepts. Keys are extensions or media types; a "default" key (or the first entry) is used when nothing matches. It responds 406 when there is no match and no default.
func (*Response) Fresh ¶
Fresh reports whether the current request is fresh against the headers set on this response (convenience wrapper around req.Fresh).
func (*Response) JSON ¶
JSON serializes v as JSON and writes it with an application/json Content-Type.
func (*Response) LastModified ¶
LastModified sets the Last-Modified header from t.
func (*Response) NotModified ¶
func (res *Response) NotModified()
NotModified sends a 304 Not Modified with no body. Use it after setting ETag or Last-Modified when the request is fresh.
func (*Response) OnBeforeWrite ¶
func (res *Response) OnBeforeWrite(fn func())
OnBeforeWrite registers a callback invoked once, immediately before the response headers are committed. Use it to set headers or cookies that depend on work done during the request (e.g. persisting a session).
func (*Response) Redirect ¶
Redirect sends a redirect response. If a status code is provided it is used; otherwise 302 Found is assumed.
func (*Response) Render ¶
Render renders a view and sends it as HTML. The view name is resolved against the app's "views" directory and "view engine" setting. Optional data is passed to the template; when omitted, res.Locals is used.
func (*Response) SSE ¶
SSE prepares the response for Server-Sent Events (sets the text/event-stream headers and flushes them) and returns a writer for emitting events. The handler should keep running to push events, typically until req context is done.
func (*Response) Send ¶
Send writes a response body. Strings and []byte are written as-is; any other value is serialized as JSON. It sets a default Content-Type when none is set.
func (*Response) SendChunked ¶
SendChunked writes data to the client split into fixed-size chunks, flushing after each. Useful for pacing a large in-memory response.
func (*Response) SendFile ¶
SendFile sends the file at path to the client. It uses http.ServeContent under the hood, so it supports Range requests, conditional GET (If-Modified-Since / If-None-Match), and content-type detection by extension. Returns an error if the file cannot be opened.
func (*Response) SendStatus ¶
SendStatus sets the status code and sends its standard text as the body.
func (*Response) SendStream ¶
SendStream copies a reader to the client in chunks, flushing as it goes. It is suited to large or open-ended payloads where buffering the whole body in memory is undesirable. chunkSize defaults to 32 KiB when <= 0.
func (*Response) StatusCode ¶
StatusCode returns the currently set status code.
func (*Response) Stream ¶
Stream streams a response body produced by fn. fn receives a writer that flushes each write to the client, so data reaches the client incrementally. The Content-Type defaults to application/octet-stream when unset.
res.Stream(func(w io.Writer) error {
for i := 0; i < 5; i++ {
fmt.Fprintf(w, "chunk %d\n", i)
}
return nil
})
func (*Response) Type ¶
Type sets the Content-Type header. Common shorthands ("json", "html", "text") are expanded; anything containing a slash is used verbatim.
func (*Response) Write ¶
Write implements io.Writer, committing the status line and headers on the first call. This lets a *Response be used directly as a streaming sink, e.g. with io.Copy or fmt.Fprintf. When no Content-Length is set, net/http streams the body using chunked transfer-encoding automatically.
func (*Response) WriteChunk ¶
WriteChunk writes a chunk and immediately flushes it to the client — the building block for chunked streaming responses.
func (*Response) WriteString ¶
WriteString writes a string chunk (without flushing).
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route binds handlers for multiple HTTP methods to a single path.
type RouteRegistrar ¶
type RouteRegistrar interface {
// Use mounts middleware, an error handler, or a sub-router, optionally
// scoped to a leading path prefix.
Use(args ...any) *Router
// All registers handlers that run for every HTTP method matching path.
All(path string, handlers ...Handler) *Router
// Get registers handlers for GET requests to path.
Get(path string, handlers ...Handler) *Router
// Post registers handlers for POST requests to path.
Post(path string, handlers ...Handler) *Router
// Put registers handlers for PUT requests to path.
Put(path string, handlers ...Handler) *Router
// Delete registers handlers for DELETE requests to path.
Delete(path string, handlers ...Handler) *Router
// Patch registers handlers for PATCH requests to path.
Patch(path string, handlers ...Handler) *Router
// Head registers handlers for HEAD requests to path.
Head(path string, handlers ...Handler) *Router
// Options registers handlers for OPTIONS requests to path.
Options(path string, handlers ...Handler) *Router
// Query registers handlers for the QUERY method.
Query(path string, handlers ...Handler) *Router
// Param registers a route-parameter callback.
Param(name string, fn ParamHandler) *Router
// Route returns a Route for registering several methods on one path.
Route(path string) *Route
}
RouteRegistrar is the route-registration surface shared by *Router and *Application. An Application embeds *Router, so both types expose exactly the same set of routing methods; capturing them in one interface documents that shared contract and lets helpers accept "anything routes can be registered on" — whether that is the top-level app or a sub-router — without depending on the concrete type.
Every method returns *Router (the receiver, or the embedded router for an Application) so registrations remain chainable.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is an isolated instance of middleware and routes. Applications embed a root Router, and additional routers can be created and mounted to compose modular route handlers.
func NewRouter ¶
func NewRouter(opts ...RouterOptions) *Router
NewRouter creates an empty Router with optional options.
func (*Router) Param ¶
func (r *Router) Param(name string, fn ParamHandler) *Router
Param registers a callback that runs when name is captured as a route parameter, once per request, before the matched route's handlers — the equivalent of Express's app.param(). Typical use is to load a record by id.
func (*Router) Query ¶
Query registers handlers for the HTTP QUERY method (https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-latest.html), a safe, idempotent method that carries a request body — like GET, but with a payload used to describe the query. Express added app.query() for it; this is the Go equivalent.
func (*Router) Route ¶
Route returns a Route bound to path, allowing several HTTP methods to be registered for the same path in a chain — the equivalent of app.route(path):
app.Route("/users").
Get(list).
Post(create)
func (*Router) Use ¶
Use mounts middleware, optionally scoped to a path prefix. It accepts an optional leading string path followed by any mix of Handler, ErrorHandler, and *Router values:
app.Use(logger) // app-wide middleware
app.Use("/api", apiRouter) // mount a sub-router at /api
app.Use(errorHandler) // error-handling middleware
type RouterOptions ¶
type RouterOptions struct {
// CaseSensitive makes route matching case-sensitive ("/Foo" != "/foo").
// The default (false) matches case-insensitively, like Express.
CaseSensitive bool
// Strict enables strict routing, distinguishing "/foo" from "/foo/".
// The default (false) treats a trailing slash as optional.
Strict bool
// MergeParams makes a mounted sub-router inherit the parameters captured by
// its parent (e.g. a :userId in the mount path). The default (false) scopes
// each router to its own parameters.
MergeParams bool
}
RouterOptions configures a Router, mirroring Express's router options.
type SSEWriter ¶
type SSEWriter struct {
// contains filtered or unexported fields
}
SSEWriter writes Server-Sent Events to the client. Obtain one with res.SSE().
func (*SSEWriter) Comment ¶
Comment emits an SSE comment line (often used as a keep-alive heartbeat).
func (*SSEWriter) Send ¶
Send emits a named event with a data payload. Multi-line data is split into multiple data: lines per the SSE spec.
type SessionData ¶
type SessionData struct {
// Values holds the session data.
Values map[string]any
// contains filtered or unexported fields
}
SessionData is the per-request session object exposed to handlers via req.Session(). Values are read and written with Get/Set; changes are persisted automatically before the response is sent.
func (*SessionData) Delete ¶
func (s *SessionData) Delete(key string)
Delete removes a session value.
func (*SessionData) Destroy ¶
func (s *SessionData) Destroy()
Destroy marks the session for removal; the cookie is cleared on response.
func (*SessionData) Get ¶
func (s *SessionData) Get(key string) (any, bool)
Get returns a session value and whether it was present.
func (*SessionData) GetString ¶
func (s *SessionData) GetString(key string) string
GetString returns a string session value, or "" if missing / not a string.
func (*SessionData) Regenerate ¶
func (s *SessionData) Regenerate() error
Regenerate issues a fresh session id, discarding the old one. Call this on privilege changes such as login to defeat session fixation.
func (*SessionData) Set ¶
func (s *SessionData) Set(key string, value any)
Set stores a session value and marks the session dirty.
type SessionOptions ¶
type SessionOptions struct {
// Name is the session cookie name (default "connect.sid").
Name string
// Store persists sessions (default an in-memory store).
Store SessionStore
// Secure marks the cookie Secure (HTTPS only).
Secure bool
// HTTPOnly marks the cookie HttpOnly (default true).
HTTPOnly bool
// SameSite sets the cookie SameSite policy (default Lax).
SameSite http.SameSite
// MaxAge sets the cookie Max-Age in seconds (0 = session cookie).
MaxAge int
}
SessionOptions configures the session middleware.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package accepts performs HTTP content negotiation based on the Accept, Accept-Language, Accept-Charset and Accept-Encoding request headers.
|
Package accepts performs HTTP content negotiation based on the Accept, Accept-Language, Accept-Charset and Accept-Encoding request headers. |
|
Package bytes converts between byte counts and human readable strings, modeled on the npm "bytes" package by TJ Holowaychuk.
|
Package bytes converts between byte counts and human readable strings, modeled on the npm "bytes" package by TJ Holowaychuk. |
|
Package camelcase converts dash/dot/underscore/space separated (and mixed-case) strings into camelCase or PascalCase, modeled on the npm "camelcase" package.
|
Package camelcase converts dash/dot/underscore/space separated (and mixed-case) strings into camelCase or PascalCase, modeled on the npm "camelcase" package. |
|
Package chunk provides a faithful port of lodash's `chunk` utility.
|
Package chunk provides a faithful port of lodash's `chunk` utility. |
|
Package contentdisposition creates and parses HTTP Content-Disposition headers.
|
Package contentdisposition creates and parses HTTP Content-Disposition headers. |
|
Package contentrange formats and parses HTTP Content-Range header values.
|
Package contentrange formats and parses HTTP Content-Range header values. |
|
Package contenttype parses and formats HTTP Content-Type header values, modeled on the npm "content-type" package and RFC 7231.
|
Package contenttype parses and formats HTTP Content-Type header values, modeled on the npm "content-type" package and RFC 7231. |
|
Package cookie parses and serializes HTTP cookie headers.
|
Package cookie parses and serializes HTTP cookie headers. |
|
Package cookiesignature signs and verifies cookie values using HMAC-SHA256, mirroring the behavior of the npm cookie-signature library.
|
Package cookiesignature signs and verifies cookie values using HMAC-SHA256, mirroring the behavior of the npm cookie-signature library. |
|
Package cryptorandomstring is a standard-library port of the npm "crypto-random-string" library.
|
Package cryptorandomstring is a standard-library port of the npm "crypto-random-string" library. |
|
Package debounce provides a faithful port of lodash's debounce.
|
Package debounce provides a faithful port of lodash's debounce. |
|
Package deburr provides a faithful port of lodash's `deburr` utility.
|
Package deburr provides a faithful port of lodash's `deburr` utility. |
|
Package deepmerge deeply merges maps, modeled on the npm "deepmerge" package.
|
Package deepmerge deeply merges maps, modeled on the npm "deepmerge" package. |
|
docs
|
|
|
gen
command
Command gendocs generates a static HTML documentation site for a Go module using only the standard library (go/doc, go/parser).
|
Command gendocs generates a static HTML documentation site for a Go module using only the standard library (go/doc, go/parser). |
|
Package dotenv parses .env style configuration content and loads it into the process environment, mirroring the behavior of the npm "dotenv" library.
|
Package dotenv parses .env style configuration content and loads it into the process environment, mirroring the behavior of the npm "dotenv" library. |
|
Package dotprop provides get/set/has/delete access to nested map[string]any structures using dotted path strings, mirroring the behavior of the npm "dot-prop" library.
|
Package dotprop provides get/set/has/delete access to nested map[string]any structures using dotted path strings, mirroring the behavior of the npm "dot-prop" library. |
|
Package encodeurl encodes a URL to a percent-encoded form, excluding already-encoded sequences.
|
Package encodeurl encodes a URL to a percent-encoded form, excluding already-encoded sequences. |
|
Package escapehtml escapes special characters in a string for safe inclusion in HTML.
|
Package escapehtml escapes special characters in a string for safe inclusion in HTML. |
|
Package escaperegexp escapes regular-expression metacharacters in a string so the string can be used as a literal inside a regular expression.
|
Package escaperegexp escapes regular-expression metacharacters in a string so the string can be used as a literal inside a regular expression. |
|
Package etag creates HTTP entity tags, a port of the npm "etag" package.
|
Package etag creates HTTP entity tags, a port of the npm "etag" package. |
|
examples
|
|
|
basic
command
Command basic demonstrates a small express application in Go.
|
Command basic demonstrates a small express application in Go. |
|
Package filesize converts a number of bytes into a human readable string.
|
Package filesize converts a number of bytes into a human readable string. |
|
Package flat flattens nested maps into single-depth maps with delimited keys and unflattens them back, mirroring the npm "flat" library.
|
Package flat flattens nested maps into single-depth maps with delimited keys and unflattens them back, mirroring the npm "flat" library. |
|
Package flatten provides faithful ports of lodash's `flatten`, `flattenDeep`, and `flattenDepth`.
|
Package flatten provides faithful ports of lodash's `flatten`, `flattenDeep`, and `flattenDepth`. |
|
Package forwarded parses the X-Forwarded-For header along with a socket remote address to produce the chain of addresses that a request traversed.
|
Package forwarded parses the X-Forwarded-For header along with a socket remote address to produce the chain of addresses that a request traversed. |
|
Package fresh implements HTTP response freshness testing, a port of the npm "fresh" package.
|
Package fresh implements HTTP response freshness testing, a port of the npm "fresh" package. |
|
Package globtoregexp converts glob patterns into regular expressions.
|
Package globtoregexp converts glob patterns into regular expressions. |
|
Package groupby provides a faithful port of lodash's `groupBy`.
|
Package groupby provides a faithful port of lodash's `groupBy`. |
|
Package hashids is a standard-library port of the Hashids algorithm (https://hashids.org).
|
Package hashids is a standard-library port of the Hashids algorithm (https://hashids.org). |
|
Package htmlentities encodes and decodes HTML entities, providing a subset of the behavior of the npm "html-entities" library.
|
Package htmlentities encodes and decodes HTML entities, providing a subset of the behavior of the npm "html-entities" library. |
|
Package httperrors provides an HTTP-aware error type modeled on the npm "http-errors" package.
|
Package httperrors provides an HTTP-aware error type modeled on the npm "http-errors" package. |
|
Package humanizeduration converts a duration in milliseconds into a human readable phrase such as "1 hour" or "1 minute, 1 second".
|
Package humanizeduration converts a duration in milliseconds into a human readable phrase such as "1 hour" or "1 minute, 1 second". |
|
Package ipaddr provides parsing and classification of IPv4 and IPv6 addresses.
|
Package ipaddr provides parsing and classification of IPv4 and IPv6 addresses. |
|
Package kebabcase converts strings to kebab-case, modeled on the npm "kebab-case" package.
|
Package kebabcase converts strings to kebab-case, modeled on the npm "kebab-case" package. |
|
Package keygrip provides signing and verification of data using a rotating list of secret keys, mirroring the behavior of the npm keygrip library.
|
Package keygrip provides signing and verification of data using a rotating list of secret keys, mirroring the behavior of the npm keygrip library. |
|
lodash
|
|
|
array
Package array provides idiomatic Go generic ports of lodash's array utility functions.
|
Package array provides idiomatic Go generic ports of lodash's array utility functions. |
|
collection
Package collection is a standalone, dependency-free port of lodash's collection utilities to Go generics.
|
Package collection is a standalone, dependency-free port of lodash's collection utilities to Go generics. |
|
datefns
Package datefns ports the most commonly used date-fns helpers to Go's time.Time.
|
Package datefns ports the most commonly used date-fns helpers to Go's time.Time. |
|
lang
Package lang ports a selection of lodash "Lang" and utility helpers to Go.
|
Package lang ports a selection of lodash "Lang" and utility helpers to Go. |
|
math
Package math provides generic ports of the math and number utility functions found in the JavaScript library lodash.
|
Package math provides generic ports of the math and number utility functions found in the JavaScript library lodash. |
|
object
Package object ports a collection of lodash object utility functions to Go.
|
Package object ports a collection of lodash object utility functions to Go. |
|
str
Package str provides ports of the string utility functions found in the JavaScript library lodash.
|
Package str provides ports of the string utility functions found in the JavaScript library lodash. |
|
Package mediatyper parses and formats HTTP media type strings of the form type/subtype+suffix; params.
|
Package mediatyper parses and formats HTTP media type strings of the form type/subtype+suffix; params. |
|
middleware
|
|
|
abtest
Package abtest provides middleware that assigns each visitor a stable A/B test bucket.
|
Package abtest provides middleware that assigns each visitor a stable A/B test bucket. |
|
acceptlanguage
Package acceptlanguage provides middleware that parses the Accept-Language request header, optionally negotiates against a set of supported languages, and stores the chosen language tag on the request under the key "language".
|
Package acceptlanguage provides middleware that parses the Accept-Language request header, optionally negotiates against a set of supported languages, and stores the chosen language tag on the request under the key "language". |
|
accesslog
Package accesslog provides middleware that writes an Apache "combined" style access log line for every request once it completes.
|
Package accesslog provides middleware that writes an Apache "combined" style access log line for every request once it completes. |
|
apikey
Package apikey provides middleware that authenticates requests using an API key supplied via a request header or query-string parameter.
|
Package apikey provides middleware that authenticates requests using an API key supplied via a request header or query-string parameter. |
|
basepath
Package basepath provides middleware that strips a fixed prefix from the request path, allowing an application mounted under a sub-path (e.g.
|
Package basepath provides middleware that strips a fixed prefix from the request path, allowing an application mounted under a sub-path (e.g. |
|
basicauth
Package basicauth provides HTTP Basic authentication middleware for the express framework.
|
Package basicauth provides HTTP Basic authentication middleware for the express framework. |
|
bearerauth
Package bearerauth provides middleware that authenticates requests using an opaque bearer token supplied in the Authorization header.
|
Package bearerauth provides middleware that authenticates requests using an opaque bearer token supplied in the Authorization header. |
|
bodylimit
Package bodylimit provides express middleware that rejects requests whose body exceeds a configured size, guarding handlers against oversized uploads.
|
Package bodylimit provides express middleware that rejects requests whose body exceeds a configured size, guarding handlers against oversized uploads. |
|
cachecontrol
Package cachecontrol provides express middleware that sets a Cache-Control header assembled from a set of caching options.
|
Package cachecontrol provides express middleware that sets a Cache-Control header assembled from a set of caching options. |
|
circuitbreaker
Package circuitbreaker provides middleware implementing the circuit-breaker pattern.
|
Package circuitbreaker provides middleware implementing the circuit-breaker pattern. |
|
compression
Package compression provides express middleware that gzip-compresses responses for clients that advertise gzip support via Accept-Encoding.
|
Package compression provides express middleware that gzip-compresses responses for clients that advertise gzip support via Accept-Encoding. |
|
concurrencylimit
Package concurrencylimit provides middleware that caps the number of requests processed concurrently.
|
Package concurrencylimit provides middleware that caps the number of requests processed concurrently. |
|
contenttypedefault
Package contenttypedefault provides express middleware that sets a default Content-Type on the response when a handler does not set one itself.
|
Package contenttypedefault provides express middleware that sets a default Content-Type on the response when a handler does not set one itself. |
|
cookieparser
Package cookieparser provides middleware that parses all cookies from the incoming request into a map[string]string and stores it on the request for convenient downstream access.
|
Package cookieparser provides middleware that parses all cookies from the incoming request into a map[string]string and stores it on the request for convenient downstream access. |
|
cookiesession
Package cookiesession implements a lightweight, cookie-only session store.
|
Package cookiesession implements a lightweight, cookie-only session store. |
|
correlationid
Package correlationid provides express middleware that assigns a correlation id to each request, used to trace a single logical operation across multiple services.
|
Package correlationid provides express middleware that assigns a correlation id to each request, used to trace a single logical operation across multiple services. |
|
cors
Package cors provides configurable Cross-Origin Resource Sharing (CORS) middleware for the express framework.
|
Package cors provides configurable Cross-Origin Resource Sharing (CORS) middleware for the express framework. |
|
crossoriginembedder
Package crossoriginembedder provides middleware that sets the Cross-Origin-Embedder-Policy (COEP) response header, which controls whether a document may load cross-origin resources that lack explicit permission.
|
Package crossoriginembedder provides middleware that sets the Cross-Origin-Embedder-Policy (COEP) response header, which controls whether a document may load cross-origin resources that lack explicit permission. |
|
crossoriginopener
Package crossoriginopener provides middleware that sets the Cross-Origin-Opener-Policy (COOP) response header, which controls whether a document may share a browsing context group with cross-origin documents.
|
Package crossoriginopener provides middleware that sets the Cross-Origin-Opener-Policy (COOP) response header, which controls whether a document may share a browsing context group with cross-origin documents. |
|
crossoriginresource
Package crossoriginresource provides middleware that sets the Cross-Origin-Resource-Policy (CORP) response header, which limits which origins may include the resource.
|
Package crossoriginresource provides middleware that sets the Cross-Origin-Resource-Policy (CORP) response header, which limits which origins may include the resource. |
|
csp
Package csp provides middleware that builds and sets a Content-Security-Policy response header from a directive map.
|
Package csp provides middleware that builds and sets a Content-Security-Policy response header from a directive map. |
|
cspnonce
Package cspnonce provides middleware that generates a per-request nonce and emits a Content-Security-Policy header whose script-src directive includes that nonce, enabling inline scripts to be allow-listed safely.
|
Package cspnonce provides middleware that generates a per-request nonce and emits a Content-Security-Policy header whose script-src directive includes that nonce, enabling inline scripts to be allow-listed safely. |
|
csrf
Package csrf provides Cross-Site Request Forgery protection using the double-submit-cookie pattern.
|
Package csrf provides Cross-Site Request Forgery protection using the double-submit-cookie pattern. |
|
decompress
Package decompress provides express middleware that transparently decompresses gzip-encoded request bodies so downstream handlers read plain data.
|
Package decompress provides express middleware that transparently decompresses gzip-encoded request bodies so downstream handlers read plain data. |
|
dnsprefetch
Package dnsprefetch provides middleware that sets the X-DNS-Prefetch-Control response header, controlling browser DNS prefetching.
|
Package dnsprefetch provides middleware that sets the X-DNS-Prefetch-Control response header, controlling browser DNS prefetching. |
|
downloadheader
Package downloadheader provides express middleware that marks responses as file downloads via the Content-Disposition header.
|
Package downloadheader provides express middleware that marks responses as file downloads via the Content-Disposition header. |
|
errorjson
Package errorjson provides an express error handler that renders unhandled errors as a JSON object of the form {"error": "<message>"}.
|
Package errorjson provides an express error handler that renders unhandled errors as a JSON object of the form {"error": "<message>"}. |
|
etag
Package etag provides express middleware that computes a strong ETag for the response body and answers conditional requests with 304 Not Modified.
|
Package etag provides express middleware that computes a strong ETag for the response body and answers conditional requests with 304 Not Modified. |
|
expectct
Package expectct provides middleware that sets the Expect-CT response header, allowing sites to opt in to reporting and/or enforcement of Certificate Transparency requirements.
|
Package expectct provides middleware that sets the Expect-CT response header, allowing sites to opt in to reporting and/or enforcement of Certificate Transparency requirements. |
|
expires
Package expires provides express middleware that sets an HTTP Expires header a fixed duration into the future.
|
Package expires provides express middleware that sets an HTTP Expires header a fixed duration into the future. |
|
favicon
Package favicon provides middleware that answers requests for /favicon.ico, short-circuiting them before they reach application routes or logging.
|
Package favicon provides middleware that answers requests for /favicon.ico, short-circuiting them before they reach application routes or logging. |
|
featureflag
Package featureflag provides middleware that attaches a set of boolean feature flags to each request, letting handlers gate behavior on named features.
|
Package featureflag provides middleware that attaches a set of boolean feature flags to each request, letting handlers gate behavior on named features. |
|
flash
Package flash implements one-time "flash" messages backed by the express session.
|
Package flash implements one-time "flash" messages backed by the express session. |
|
forcessl
Package forcessl provides middleware that redirects insecure HTTP requests to their HTTPS equivalent, preserving the host, path, and query string.
|
Package forcessl provides middleware that redirects insecure HTTP requests to their HTTPS equivalent, preserving the host, path, and query string. |
|
frameguard
Package frameguard provides middleware that sets the X-Frame-Options response header to control whether the page may be rendered inside a frame, helping to mitigate clickjacking attacks.
|
Package frameguard provides middleware that sets the X-Frame-Options response header to control whether the page may be rendered inside a frame, helping to mitigate clickjacking attacks. |
|
healthcheck
Package healthcheck provides a liveness/readiness endpoint for the express framework.
|
Package healthcheck provides a liveness/readiness endpoint for the express framework. |
|
healthz
Package healthz provides a minimal liveness endpoint.
|
Package healthz provides a minimal liveness endpoint. |
|
helmet
Package helmet bundles a sensible set of security-related HTTP response headers into a single express middleware, mirroring the popular Node.js Helmet defaults.
|
Package helmet bundles a sensible set of security-related HTTP response headers into a single express middleware, mirroring the popular Node.js Helmet defaults. |
|
hidepoweredby
Package hidepoweredby provides middleware that removes the X-Powered-By response header (or replaces it with a decoy value) so the server does not advertise the technology stack it runs on.
|
Package hidepoweredby provides middleware that removes the X-Powered-By response header (or replaces it with a decoy value) so the server does not advertise the technology stack it runs on. |
|
hmacauth
Package hmacauth provides middleware that authenticates requests by verifying an HMAC-SHA256 signature of the request body against a shared secret.
|
Package hmacauth provides middleware that authenticates requests by verifying an HMAC-SHA256 signature of the request body against a shared secret. |
|
hostcheck
Package hostcheck provides middleware that guards against Host header attacks by permitting only requests whose hostname is in a configured allowlist.
|
Package hostcheck provides middleware that guards against Host header attacks by permitting only requests whose hostname is in a configured allowlist. |
|
hsts
Package hsts provides middleware that sets the HTTP Strict-Transport-Security (HSTS) response header, instructing browsers to only access the site over HTTPS.
|
Package hsts provides middleware that sets the HTTP Strict-Transport-Security (HSTS) response header, instructing browsers to only access the site over HTTPS. |
|
ienoopen
Package ienoopen provides middleware that sets X-Download-Options: noopen, preventing Internet Explorer from executing downloads in the site's context.
|
Package ienoopen provides middleware that sets X-Download-Options: noopen, preventing Internet Explorer from executing downloads in the site's context. |
|
ipallowlist
Package ipallowlist provides middleware that only permits requests whose client IP matches a configured allowlist of addresses or CIDR ranges.
|
Package ipallowlist provides middleware that only permits requests whose client IP matches a configured allowlist of addresses or CIDR ranges. |
|
ipblocklist
Package ipblocklist provides middleware that rejects requests whose client IP matches a configured blocklist of addresses or CIDR ranges.
|
Package ipblocklist provides middleware that rejects requests whose client IP matches a configured blocklist of addresses or CIDR ranges. |
|
jsonp
Package jsonp provides express middleware that wraps JSON responses in a JavaScript callback invocation when the request carries a callback query parameter, enabling cross-origin JSONP requests.
|
Package jsonp provides express middleware that wraps JSON responses in a JavaScript callback invocation when the request carries a callback query parameter, enabling cross-origin JSONP requests. |
|
jwtauth
Package jwtauth provides middleware that verifies HS256-signed JSON Web Tokens supplied via the Authorization header.
|
Package jwtauth provides middleware that verifies HS256-signed JSON Web Tokens supplied via the Authorization header. |
|
latencyheader
Package latencyheader provides middleware that measures how long a request takes to process and records the elapsed milliseconds in a response header (X-Response-Latency by default).
|
Package latencyheader provides middleware that measures how long a request takes to process and records the elapsed milliseconds in a response header (X-Response-Latency by default). |
|
maintenance
Package maintenance provides middleware that puts an application into maintenance mode.
|
Package maintenance provides middleware that puts an application into maintenance mode. |
|
methodallow
Package methodallow provides middleware that restricts requests to a configured set of HTTP methods, responding with 405 otherwise.
|
Package methodallow provides middleware that restricts requests to a configured set of HTTP methods, responding with 405 otherwise. |
|
methodoverride
Package methodoverride provides middleware that overrides the HTTP request method using either a request header or a query-string parameter.
|
Package methodoverride provides middleware that overrides the HTTP request method using either a request header or a query-string parameter. |
|
metrics
Package metrics provides middleware that records basic request metrics for the express framework: the total number of requests and a breakdown by status class (2xx, 3xx, 4xx, 5xx).
|
Package metrics provides middleware that records basic request metrics for the express framework: the total number of requests and a breakdown by status class (2xx, 3xx, 4xx, 5xx). |
|
nocache
Package nocache provides express middleware that instructs clients and proxies never to cache the response.
|
Package nocache provides express middleware that instructs clients and proxies never to cache the response. |
|
nonce
Package nonce provides middleware that generates a fresh, random, base64-encoded nonce for each request.
|
Package nonce provides middleware that generates a fresh, random, base64-encoded nonce for each request. |
|
nosniff
Package nosniff provides middleware that sets X-Content-Type-Options: nosniff to prevent browsers from MIME-sniffing a response away from the declared Content-Type.
|
Package nosniff provides middleware that sets X-Content-Type-Options: nosniff to prevent browsers from MIME-sniffing a response away from the declared Content-Type. |
|
notfound
Package notfound provides a terminal handler that responds with 404 Not Found.
|
Package notfound provides a terminal handler that responds with 404 Not Found. |
|
originagentcluster
Package originagentcluster provides middleware that sets the Origin-Agent-Cluster response header, requesting that the browser isolate the origin into its own agent cluster.
|
Package originagentcluster provides middleware that sets the Origin-Agent-Cluster response header, requesting that the browser isolate the origin into its own agent cluster. |
|
origincheck
Package origincheck provides middleware that rejects requests whose Origin header is not in a configured allowlist, mitigating cross-site request forgery from untrusted origins.
|
Package origincheck provides middleware that rejects requests whose Origin header is not in a configured allowlist, mitigating cross-site request forgery from untrusted origins. |
|
pagination
Package pagination provides middleware that parses common "page" and "limit" query-string parameters into a normalized, bounds-checked Pagination value stored on the request.
|
Package pagination provides middleware that parses common "page" and "limit" query-string parameters into a normalized, bounds-checked Pagination value stored on the request. |
|
panicjson
Package panicjson provides middleware that recovers from panics in downstream handlers, logs them, and responds with a generic 500 JSON error so a single failing request cannot crash the server.
|
Package panicjson provides middleware that recovers from panics in downstream handlers, logs them, and responds with a generic 500 JSON error so a single failing request cannot crash the server. |
|
permittedcrossdomain
Package permittedcrossdomain provides middleware that sets the X-Permitted-Cross-Domain-Policies response header, controlling Adobe Flash/Acrobat cross-domain policy files.
|
Package permittedcrossdomain provides middleware that sets the X-Permitted-Cross-Domain-Policies response header, controlling Adobe Flash/Acrobat cross-domain policy files. |
|
poweredby
Package poweredby provides express middleware that sets the X-Powered-By response header to a configurable value.
|
Package poweredby provides express middleware that sets the X-Powered-By response header to a configurable value. |
|
querylimit
Package querylimit provides middleware that rejects requests whose raw query string exceeds a configured maximum length.
|
Package querylimit provides middleware that rejects requests whose raw query string exceeds a configured maximum length. |
|
querynormalize
Package querynormalize provides middleware that normalizes the request query string: it lower-cases parameter keys, trims surrounding whitespace from values, and rebuilds the raw query in a deterministic (key-sorted) order.
|
Package querynormalize provides middleware that normalizes the request query string: it lower-cases parameter keys, trims surrounding whitespace from values, and rebuilds the raw query in a deterministic (key-sorted) order. |
|
ratelimit
Package ratelimit provides a fixed-window, per-client rate limiter for the express framework.
|
Package ratelimit provides a fixed-window, per-client rate limiter for the express framework. |
|
rawbody
Package rawbody provides express middleware that reads the entire request body into memory, stores it on the request via SetBody, and restores req.Raw.Body so downstream handlers can read it again.
|
Package rawbody provides express middleware that reads the entire request body into memory, stores it on the request via SetBody, and restores req.Raw.Body so downstream handlers can read it again. |
|
readiness
Package readiness provides a readiness-probe endpoint for the express framework.
|
Package readiness provides a readiness-probe endpoint for the express framework. |
|
realip
Package realip provides middleware that determines the true client IP address from the X-Forwarded-For and X-Real-IP headers, taking an optional list of trusted proxies into account, and rewrites req.Raw.RemoteAddr to it.
|
Package realip provides middleware that determines the true client IP address from the X-Forwarded-For and X-Real-IP headers, taking an optional list of trusted proxies into account, and rewrites req.Raw.RemoteAddr to it. |
|
redirectmap
Package redirectmap provides middleware that redirects requests whose path matches an entry in a static lookup table.
|
Package redirectmap provides middleware that redirects requests whose path matches an entry in a static lookup table. |
|
referer
Package referer provides middleware that captures the Referer request header, parses out its host, and stores the result on the request under the key "referer" for downstream handlers (analytics, anti-CSRF checks, etc.).
|
Package referer provides middleware that captures the Referer request header, parses out its host, and stores the result on the request under the key "referer" for downstream handlers (analytics, anti-CSRF checks, etc.). |
|
referercheck
Package referercheck provides middleware that rejects requests whose Referer header host is not in a configured allowlist.
|
Package referercheck provides middleware that rejects requests whose Referer header host is not in a configured allowlist. |
|
referrerpolicy
Package referrerpolicy provides middleware that sets the Referrer-Policy response header, controlling how much referrer information is included with requests.
|
Package referrerpolicy provides middleware that sets the Referrer-Policy response header, controlling how much referrer information is included with requests. |
|
requestcontext
Package requestcontext provides middleware that attaches a small request-scoped context to each request: a unique request ID and a start timestamp.
|
Package requestcontext provides middleware that attaches a small request-scoped context to each request: a unique request ID and a start timestamp. |
|
requestcounter
Package requestcounter provides middleware that counts the total number of requests handled.
|
Package requestcounter provides middleware that counts the total number of requests handled. |
|
requestdump
Package requestdump provides development middleware that records a snapshot of each incoming request (method, path, and headers) into a bounded, thread-safe ring buffer.
|
Package requestdump provides development middleware that records a snapshot of each incoming request (method, path, and headers) into a bounded, thread-safe ring buffer. |
|
requestid
Package requestid provides express middleware that assigns each request a unique identifier, echoes it on the response, and stores it on the request for downstream handlers and logging.
|
Package requestid provides express middleware that assigns each request a unique identifier, echoes it on the response, and stores it on the request for downstream handlers and logging. |
|
requireauth
Package requireauth provides middleware that rejects requests unless an authenticated user has been placed on the request by earlier middleware.
|
Package requireauth provides middleware that rejects requests unless an authenticated user has been placed on the request by earlier middleware. |
|
responsecache
Package responsecache provides simple in-memory caching of successful GET responses.
|
Package responsecache provides simple in-memory caching of successful GET responses. |
|
responsetime
Package responsetime provides express middleware that measures how long a request takes to process and reports it in an X-Response-Time header.
|
Package responsetime provides express middleware that measures how long a request takes to process and reports it in an X-Response-Time header. |
|
retryafter
Package retryafter provides middleware that automatically attaches a Retry-After header to responses whose status indicates the client should back off (429 Too Many Requests and 503 Service Unavailable).
|
Package retryafter provides middleware that automatically attaches a Retry-After header to responses whose status indicates the client should back off (429 Too Many Requests and 503 Service Unavailable). |
|
rewrite
Package rewrite provides URL-rewriting middleware.
|
Package rewrite provides URL-rewriting middleware. |
|
rolecheck
Package rolecheck provides middleware that authorizes requests only when the caller holds at least one of the required roles.
|
Package rolecheck provides middleware that authorizes requests only when the caller holds at least one of the required roles. |
|
sanitize
Package sanitize provides middleware that strips HTML tags from all query-string values on the incoming request, mitigating trivial reflected XSS vectors that flow through query parameters.
|
Package sanitize provides middleware that strips HTML tags from all query-string values on the incoming request, mitigating trivial reflected XSS vectors that flow through query parameters. |
|
scopecheck
Package scopecheck provides middleware that authorizes requests only when the caller holds all of the required scopes.
|
Package scopecheck provides middleware that authorizes requests only when the caller holds all of the required scopes. |
|
serveindex
Package serveindex provides middleware that renders an HTML directory listing for requests that resolve to a directory beneath a configured root.
|
Package serveindex provides middleware that renders an HTML directory listing for requests that resolve to a directory beneath a configured root. |
|
servertiming
Package servertiming provides express middleware that collects timing metrics during request handling and emits them in a Server-Timing response header, which browsers surface in their developer tools.
|
Package servertiming provides express middleware that collects timing metrics during request handling and emits them in a Server-Timing response header, which browsers surface in their developer tools. |
|
signedcookies
Package signedcookies provides middleware that verifies a tamper-evident, HMAC-signed cookie and exposes its value to downstream handlers.
|
Package signedcookies provides middleware that verifies a tamper-evident, HMAC-signed cookie and exposes its value to downstream handlers. |
|
slowdown
Package slowdown provides middleware that progressively delays responses for a client once it exceeds a configured request threshold within a fixed window.
|
Package slowdown provides middleware that progressively delays responses for a client once it exceeds a configured request threshold within a fixed window. |
|
slowlog
Package slowlog provides middleware that logs a warning whenever a request takes longer than a configured threshold to complete, helping surface slow endpoints.
|
Package slowlog provides middleware that logs a warning whenever a request takes longer than a configured threshold to complete, helping surface slow endpoints. |
|
spa
Package spa provides middleware for serving single-page applications.
|
Package spa provides middleware for serving single-page applications. |
|
subdomain
Package subdomain provides middleware that extracts the subdomain portion of the request's hostname and stores it on the request for downstream handlers under the key "subdomain".
|
Package subdomain provides middleware that extracts the subdomain portion of the request's hostname and stores it on the request for downstream handlers under the key "subdomain". |
|
throttle
Package throttle provides a per-client token-bucket rate limiter for the express framework.
|
Package throttle provides a per-client token-bucket rate limiter for the express framework. |
|
timeout
Package timeout provides middleware that bounds the time a downstream handler chain may take.
|
Package timeout provides middleware that bounds the time a downstream handler chain may take. |
|
tokenheader
Package tokenheader provides generic middleware that validates a token supplied in a single configurable request header.
|
Package tokenheader provides generic middleware that validates a token supplied in a single configurable request header. |
|
trailingslash
Package trailingslash provides middleware that enforces a consistent trailing-slash policy by redirecting requests that do not conform.
|
Package trailingslash provides middleware that enforces a consistent trailing-slash policy by redirecting requests that do not conform. |
|
uptime
Package uptime provides middleware that reports how long the middleware (and, by extension, the process) has been running.
|
Package uptime provides middleware that reports how long the middleware (and, by extension, the process) has been running. |
|
useragent
Package useragent provides middleware that performs lightweight parsing of the User-Agent request header into a small struct and stores it on the request for downstream handlers under the key "useragent".
|
Package useragent provides middleware that performs lightweight parsing of the User-Agent request header into a small struct and stores it on the request for downstream handlers under the key "useragent". |
|
useragentblock
Package useragentblock provides middleware that rejects requests whose User-Agent header contains any configured blocked substring.
|
Package useragentblock provides middleware that rejects requests whose User-Agent header contains any configured blocked substring. |
|
vary
Package vary provides express middleware that appends fields to the response Vary header, signalling which request headers a cached response depends on.
|
Package vary provides express middleware that appends fields to the response Vary header, signalling which request headers a cached response depends on. |
|
version
Package version provides middleware that exposes an application's version.
|
Package version provides middleware that exposes an application's version. |
|
vhost
Package vhost provides virtual-host middleware that dispatches requests to a dedicated handler based on the request's hostname.
|
Package vhost provides virtual-host middleware that dispatches requests to a dedicated handler based on the request's hostname. |
|
xssfilter
Package xssfilter provides middleware that sets the legacy X-XSS-Protection response header.
|
Package xssfilter provides middleware that sets the legacy X-XSS-Protection response header. |
|
Package mimetypes provides MIME type lookups by filename or extension and reverse lookups from MIME type to extension.
|
Package mimetypes provides MIME type lookups by filename or extension and reverse lookups from MIME type to extension. |
|
Package ms converts between time durations and human readable strings, modeled on the npm "ms" package.
|
Package ms converts between time durations and human readable strings, modeled on the npm "ms" package. |
|
Package negotiator is an HTTP content negotiation helper, a port of the npm "negotiator" package.
|
Package negotiator is an HTTP content negotiation helper, a port of the npm "negotiator" package. |
|
Package onfinished registers callbacks that run when an HTTP response finishes, mirroring the behavior of the npm on-finished library in an idiomatic, httptest-friendly way.
|
Package onfinished registers callbacks that run when an HTTP response finishes, mirroring the behavior of the npm on-finished library in an idiomatic, httptest-friendly way. |
|
Package otpauth builds and parses otpauth:// key URIs.
|
Package otpauth builds and parses otpauth:// key URIs. |
|
Package parseurl parses the URL of an incoming HTTP request into its components.
|
Package parseurl parses the URL of an incoming HTTP request into its components. |
|
Package pbkdf2hash implements PBKDF2-HMAC-SHA256 key derivation and a Django-style password hash encoding.
|
Package pbkdf2hash implements PBKDF2-HMAC-SHA256 key derivation and a Django-style password hash encoding. |
|
Package plimit provides a faithful port of the npm p-limit library: it runs an unbounded number of scheduled functions while capping the number that execute concurrently.
|
Package plimit provides a faithful port of the npm p-limit library: it runs an unbounded number of scheduled functions while capping the number that execute concurrently. |
|
Package pluralize pluralizes and singularizes English words.
|
Package pluralize pluralizes and singularizes English words. |
|
Package prettybytes converts a number of bytes to a human readable string.
|
Package prettybytes converts a number of bytes to a human readable string. |
|
Package proxyaddr determines the real client address of a request that has passed through one or more trusted reverse proxies.
|
Package proxyaddr determines the real client address of a request that has passed through one or more trusted reverse proxies. |
|
Package qs parses and serializes URL query strings with support for nested objects and arrays via bracket notation.
|
Package qs parses and serializes URL query strings with support for nested objects and arrays via bracket notation. |
|
Package querystringlite is a faithful port of Node.js's built-in querystring module for flat (non-nested) query strings.
|
Package querystringlite is a faithful port of Node.js's built-in querystring module for flat (non-nested) query strings. |
|
Package randomstring is a standard-library port of the npm "randomstring" library.
|
Package randomstring is a standard-library port of the npm "randomstring" library. |
|
Package rangeparser parses the HTTP Range header, a port of the npm "range-parser" package.
|
Package rangeparser parses the HTTP Range header, a port of the npm "range-parser" package. |
|
Package retry provides a faithful port of the npm p-retry / async-retry libraries: it retries a function with exponential backoff.
|
Package retry provides a faithful port of the npm p-retry / async-retry libraries: it retries a function with exponential backoff. |
|
Package sanitizehtml sanitizes untrusted HTML by removing disallowed tags and attributes, mirroring a practical subset of the npm "sanitize-html" library.
|
Package sanitizehtml sanitizes untrusted HTML by removing disallowed tags and attributes, mirroring a practical subset of the npm "sanitize-html" library. |
|
Package sha256hex provides hex-encoded hashing and HMAC helpers.
|
Package sha256hex provides hex-encoded hashing and HMAC helpers. |
|
Package shortid is a standard-library short, URL-friendly unique id generator inspired by the npm "shortid" library.
|
Package shortid is a standard-library short, URL-friendly unique id generator inspired by the npm "shortid" library. |
|
Package slugify converts strings into URL-safe slugs, mirroring the behavior of the npm "slugify" library: accented Latin characters are transliterated to ASCII, whitespace is collapsed to a separator, and disallowed characters are removed.
|
Package slugify converts strings into URL-safe slugs, mirroring the behavior of the npm "slugify" library: accented Latin characters are transliterated to ASCII, whitespace is collapsed to a separator, and disallowed characters are removed. |
|
Package snowflake is a standard-library implementation of the Twitter Snowflake distributed ID scheme: a 63-bit id composed of a 41-bit millisecond timestamp (relative to a custom epoch), a 10-bit node id and a 12-bit per-millisecond sequence.
|
Package snowflake is a standard-library implementation of the Twitter Snowflake distributed ID scheme: a 63-bit id composed of a 41-bit millisecond timestamp (relative to a custom epoch), a 10-bit node id and a 12-bit per-millisecond sequence. |
|
Package sqlstring provides MySQL-style value and identifier escaping and query formatting, mirroring the npm "sqlstring" library.
|
Package sqlstring provides MySQL-style value and identifier escaping and query formatting, mirroring the npm "sqlstring" library. |
|
Package statuses maps between HTTP status codes and their reason phrases, modeled on the npm "statuses" package.
|
Package statuses maps between HTTP status codes and their reason phrases, modeled on the npm "statuses" package. |
|
Package striptags removes HTML tags from a string while keeping the text content, mirroring the behavior of the npm "striptags" library.
|
Package striptags removes HTML tags from a string while keeping the text content, mirroring the behavior of the npm "striptags" library. |
|
Package throttle provides a faithful port of lodash's throttle.
|
Package throttle provides a faithful port of lodash's throttle. |
|
Package titlecase converts strings to Title Case.
|
Package titlecase converts strings to Title Case. |
|
Package truncate shortens a string to a maximum length, appending an ellipsis.
|
Package truncate shortens a string to a maximum length, appending an ellipsis. |
|
Package typeis matches Content-Type header values against a set of type candidates.
|
Package typeis matches Content-Type header values against a set of type candidates. |
|
Package uidsafe generates cryptographically secure, URL-safe unique identifiers, mirroring the behavior of the npm uid-safe library.
|
Package uidsafe generates cryptographically secure, URL-safe unique identifiers, mirroring the behavior of the npm uid-safe library. |
|
Package uniq provides faithful ports of lodash's `uniq` and `uniqBy`.
|
Package uniq provides faithful ports of lodash's `uniq` and `uniqBy`. |
|
Package urljoin joins URL path segments together, normalizing slashes.
|
Package urljoin joins URL path segments together, normalizing slashes. |
|
Package validator provides lightweight, fluent input validation for express handlers, in the spirit of Node's express-validator.
|
Package validator provides lightweight, fluent input validation for express handlers, in the spirit of Node's express-validator. |
|
Package validatorjs is a standalone port of the popular npm validator.js / validatorjs string validation library to idiomatic Go.
|
Package validatorjs is a standalone port of the popular npm validator.js / validatorjs string validation library to idiomatic Go. |
|
Package vary manipulates the HTTP Vary response header, a port of the npm "vary" package.
|
Package vary manipulates the HTTP Vary response header, a port of the npm "vary" package. |
|
Package wordwrap wraps text to a fixed width, modeled on the npm "word-wrap" package.
|
Package wordwrap wraps text to a fixed width, modeled on the npm "word-wrap" package. |