express

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 23 Imported by: 0

README ¶

express

Go Test Go Lint Go Vuln Web Unit Web E2E Go Reference Go Report Card Go Version Release Last Commit Code Size PRs Welcome Docs

Node's Express, for Go.

express is a fast, minimalist web framework for Go modeled after Express.js. It gives you the familiar Express routing API — app.Get, app.Post, app.Use, route parameters, middleware chains, mountable routers — and chainable request/response helpers, all built on top of the standard library's net/http.

package main

import (
	"log"

	"github.com/malcolmston/express"
)

func main() {
	app := express.New()

	app.Get("/", func(req *express.Request, res *express.Response, next express.Next) {
		res.Send("Hello World")
	})

	log.Fatal(app.Listen(":3000"))
}

Install

go get github.com/malcolmston/express

Concepts

The handler signature

Every handler has the same three-argument shape as Express:

func(req *express.Request, res *express.Response, next express.Next)

Call next() to pass control to the next matching handler, or next(err) to jump to error-handling middleware.

Routing
app.Get("/users/:id", handler)     // GET with a route parameter
app.Post("/users", handler)        // POST
app.Put("/users/:id", handler)
app.Delete("/users/:id", handler)
app.Patch("/users/:id", handler)
app.All("/health", handler)        // any method
app.Query("/search", handler)      // the new HTTP QUERY method (safe, with a body)

The QUERY method is the emerging IETF safe-with-body method; app.Query mirrors Express's app.query().

Route parameters are read with req.Params("id"). A * in a path is a wildcard captured as the * parameter. Parameters can be optional (:id?) or constrained by a regular expression (:id(\d+)):

app.Get("/users/:id?", handler)      // matches /users and /users/42
app.Get(`/items/:id(\d+)`, handler)  // matches /items/42, not /items/abc

Register method handlers for one path with app.Route, and preprocess a parameter with app.Param:

app.Route("/users").Get(list).Post(create)
app.Param("id", func(req *express.Request, res *express.Response, next express.Next, id string) {
	user, err := db.Find(id)
	if err != nil { next(err); return }
	req.Set("user", user)
	next()
})
Middleware
app.Use(express.Logger())          // app-wide middleware
app.Use(express.Recover())         // recover from panics -> 500
app.Use(express.JSON())            // parse JSON bodies into req.Body()
app.Use("/admin", requireAuth)     // middleware scoped to a path prefix

Middleware runs in registration order. Any handler may short-circuit by writing a response and simply not calling next().

Mountable routers
api := express.NewRouter()
api.Get("/users/:id", getUser)
api.Post("/users", createUser)

app.Use("/api", api)   // routes become /api/users/:id, /api/users

Routers accept options and can be mounted at a parameterized path; use MergeParams so the sub-router sees the parent's captured params:

users := express.NewRouter(express.RouterOptions{
	MergeParams:   true,  // inherit parent params (e.g. :userId)
	CaseSensitive: false, // "/Foo" == "/foo" (default)
	Strict:        false, // "/foo" == "/foo/" (default)
})
users.Get("/profile", func(req *express.Request, res *express.Response, next express.Next) {
	res.Send("profile of " + req.Params("userId"))
})
app.Use("/users/:userId", users) // GET /users/42/profile -> "profile of 42"

Routers nest arbitrarily, each with its own middleware, params, and options.

Error handling

Register a four-argument error handler with Use; it runs only when an upstream handler calls next(err):

app.Use(func(err error, req *express.Request, res *express.Response, next express.Next) {
	res.Status(500).JSON(map[string]string{"error": err.Error()})
})

Request helpers

Method Description
req.Params(name) route parameter
req.SetPath(p) rewrite the path and the router's match path (re-routes)
req.Query(name) query-string value
req.Get(field) request header
req.Body() parsed body (after a body-parser middleware)
req.BodyJSON(&dst) read + unmarshal the JSON body into dst
req.Is("json") content-type test
req.Cookie(name) read a cookie
req.IP(), req.Hostname(), req.Protocol(), req.Secure() connection info

Response helpers

Method Description
res.Status(code) set the status code (chainable)
res.Send(body) send a string, []byte, or JSON-serializable value
res.JSON(v) send v as JSON
res.SendStatus(code) send the status text for code
res.Set(field, value) set a header
res.Type(t) set Content-Type ("json", "html", ...)
res.Redirect(url) / res.Redirect(code, url) redirect
res.Cookie(name, value, opts) set a cookie
res.SendFile(path) send a file (Range + conditional GET support)
res.Download(path, name) / res.Attachment(name) send as a download
res.Render(view, data) render a template (see Views)
res.Format(map) content negotiation by Accept
res.ETag(tag) / res.LastModified(t) / res.NotModified() conditional GET
res.End() finish with no body

Request negotiation helpers: req.Accepts(...), req.AcceptsLanguages(...), req.AcceptsCharsets(...), req.AcceptsEncodings(...), req.Ranges(size), and req.Fresh(res) / req.Stale(res).

Views

Register a template engine and render views with res.Render. The built-in engine uses html/template (for .html / .tmpl); plug in any engine with app.Engine.

app.Set("views", "./views")     // template directory (default "views")
app.Set("view engine", "html")  // default extension

app.Get("/", func(req *express.Request, res *express.Response, next express.Next) {
	res.Render("index", map[string]any{"Title": "Home"})
})

// Custom engine:
app.Engine(".mustache", func(path string, data any) (string, error) { ... })

Most response methods return *Response so they can be chained: res.Status(201).JSON(user).

Bundled middleware

  • express.JSON() — parse application/json bodies into req.Body().
  • express.URLEncoded() — parse form-encoded bodies.
  • express.Text() — parse text/plain bodies into req.Body().
  • express.Multipart(maxMemory) — parse multipart/form-data (file uploads).
  • express.Static(root) — serve static files from a directory.
  • express.Session(opts...) — cookie-backed sessions (see below).
  • express.Logger() — log method, path, status, and duration.
  • express.Recover() — recover from panics and return a 500.

Middleware suite (100+ packages)

Beyond the bundled middleware above, express ships a large catalog of ready-to-use middleware under middleware/ — over 100 independent subpackages spanning security headers, authentication/access control, body & response transforms, rate limiting & traffic control, routing/static helpers, cookies/CSRF/sessions, and dev utilities. Each has a New(...) constructor and is standard-library only.

import (
	"github.com/malcolmston/express/middleware/cors"
	"github.com/malcolmston/express/middleware/helmet"
	"github.com/malcolmston/express/middleware/ratelimit"
	"github.com/malcolmston/express/middleware/compression"
)

app.Use(helmet.New())
app.Use(cors.New(cors.Options{AllowOrigins: []string{"https://example.com"}}))
app.Use(compression.New())
app.Use(ratelimit.New(ratelimit.Options{Max: 100, Window: time.Minute}))

See MIDDLEWARE.md for the full catalog.

Sessions

express.Session() adds a cookie-backed session, persisted through a pluggable SessionStore (an in-memory store is the default). Read and write it with req.Session(); changes are saved automatically just before the response is sent.

app.Use(express.Session(express.SessionOptions{
	Name:   "sid",
	Secure: true, // HTTPS only
	// Store: myRedisStore,
}))

app.Post("/login", func(req *express.Request, res *express.Response, next express.Next) {
	sess := req.Session()
	sess.Regenerate()          // new id on privilege change (anti-fixation)
	sess.Set("userID", "42")
	res.Send("logged in")
})

app.Get("/me", func(req *express.Request, res *express.Response, next express.Next) {
	res.Send("user " + req.Session().GetString("userID"))
})

app.Post("/logout", func(req *express.Request, res *express.Response, next express.Next) {
	req.Session().Destroy()
	res.Send("bye")
})

File uploads & forms

app.Use(express.Multipart(0)) // 0 = 32 MiB default in-memory buffer

app.Post("/avatar", func(req *express.Request, res *express.Response, next express.Next) {
	file, header, err := req.FormFile("avatar")
	if err != nil {
		next(err)
		return
	}
	defer file.Close()
	res.JSON(map[string]any{"filename": header.Filename, "caption": req.FormValue("caption")})
})

req.Form() returns all form values (query + body) as url.Values; req.Files(name) returns every uploaded file header for a field.

Input validation

The validator subpackage provides fluent request validation in the spirit of express-validator. Build a Schema and mount it as middleware that rejects invalid requests with a 400 JSON body — or call Validate on a map directly.

import "github.com/malcolmston/express/validator"

schema := validator.Schema{
	validator.Field("email").Required().Email(),
	validator.Field("age").Optional().IsInt().Min(0).Max(120),
	validator.Field("name").Required().MinLen(2).MaxLen(50),
	validator.Field("role").Required().In("admin", "user"),
}

app.Use(express.JSON())
app.Post("/users", schema.Body(), createUser) // 400 {"errors":[...]} on failure

Available rules: Required, Optional, Email, MinLen, MaxLen, Min, Max, IsInt, IsNumber, In, Matches, and Custom. Use schema.Query() to validate the query string instead of the body.

Streaming & chunked responses

The response supports incremental, flushed output for large or open-ended bodies. *Response implements io.Writer, so it drops into io.Copy and fmt.Fprintf.

// Stream a body chunk-by-chunk (each write is flushed to the client).
app.Get("/stream", func(req *express.Request, res *express.Response, next express.Next) {
	res.Type("text").Stream(func(w io.Writer) error {
		for i := 0; i < 10; i++ {
			fmt.Fprintf(w, "line %d\n", i)
		}
		return nil
	})
})

// Copy a large reader to the client in chunks without buffering it all.
res.SendStream(file)               // default 32 KiB chunks
res.SendChunked(bigBytes, 64<<10)  // fixed-size chunks from memory
res.WriteChunk([]byte("partial"))  // low-level: write + flush
res.Flush()                        // flush buffered data
Server-Sent Events
app.Get("/events", func(req *express.Request, res *express.Response, next express.Next) {
	sse := res.SSE() // sets text/event-stream headers and flushes them
	for {
		select {
		case <-req.Raw.Context().Done():
			return
		case ev := <-updates:
			sse.SendJSON("update", ev)   // event: update\ndata: {...}
		case <-ticker.C:
			sse.Comment("keep-alive")
		}
	}
})

SSEWriter provides Send, SendData, SendJSON, SendID (for Last-Event-ID resumption), Comment, and Retry.

API documentation (app.Docs)

app.Docs() introspects every route you have registered — including those on mounted sub-routers — and serves live, standards-compliant API documentation with no code generation step and no third-party dependencies. One call mounts an OpenAPI 3.1 spec, interactive Swagger UI and ReDoc pages, a YAML rendering, an AsyncAPI 2.6 document for socket/event channels, and a Postman collection.

app := express.New()

app.Get("/users", listUsers)
app.Post("/users", createUser)
app.Get("/users/:id", getUser)

// Introspection knows the method, path and :id parameter automatically.
// Describe adds the parts it can't infer.
app.Describe("POST", "/users", express.RouteDoc{
	Summary: "Create a user",
	Tags:    []string{"users"},
	RequestBody: &express.BodyDoc{
		Required: true,
		Schema:   map[string]any{"type": "object", "required": []any{"name"}},
	},
	Responses: map[string]express.ResponseDoc{
		"201": {Description: "Created", Schema: map[string]any{"type": "object"}},
	},
})

// Document socket/event channels for the AsyncAPI spec.
app.Channel("chat.message", express.ChannelDoc{
	Description: "Live chat messages",
	Subscribe:   &express.MessageDoc{Name: "messageReceived", Payload: map[string]any{"type": "object"}},
})

app.Docs(express.DocsOptions{
	Title:   "My API",
	Version: "1.0.0",
	Servers: []string{"https://api.example.com"},
})

This mounts, by default:

Path Content
/docs Swagger UI
/redoc ReDoc
/openapi.json OpenAPI 3.1 specification (JSON)
/openapi.yaml OpenAPI 3.1 specification (YAML)
/asyncapi.json AsyncAPI 2.6 document (event/socket channels)
/postman.json Postman v2.1 collection

Every path is configurable via DocsOptions (set any to "-" to disable), and an Enrich hook can customise each generated operation programmatically. The specs are rebuilt per request, so routes registered after Docs() still appear. You can also obtain the documents directly — app.Routes(), app.OpenAPI(), app.OpenAPIYAML(), app.AsyncAPI(), app.PostmanCollection() — to serve or persist them however you like.

Using with net/http

An *express.Application is an http.Handler, so it drops into anything that speaks net/http — http.Server, httptest, or other middleware:

srv := &http.Server{Addr: ":8080", Handler: app}
srv.ListenAndServe()

Example

A runnable example lives in examples/basic:

go run ./examples/basic

Compatibility

This is a Go re-implementation modeled on Express.js, targeting API/behavior parity and standards-compliant HTTP output. See COMPATIBILITY.md for a feature-by-feature parity table and known gaps.

Companion library

Pair this with passport — a Go port of Passport.js — for pluggable authentication.

License

MIT

Documentation ¶

Overview ¶

Package express is a fast, minimalist web framework for Go, modeled after the Node.js Express framework. It is a stdlib-only port: everything is built on net/http and the standard library, with no third-party dependencies, so it drops cleanly into any Go project and interoperates with the wider net/http ecosystem. The goal is to give Go programmers the ergonomics that made Express popular — declarative routing, a chainable request/response API, and a composable middleware stack — while remaining idiomatic Go underneath.

Core model ¶

The core model mirrors Express's four building blocks: the Application, the Router, the Request, and the Response. express.New returns an *Application, which embeds a *Router; because of that embedding every routing method lives directly on the app — app.Use, app.Get, app.Post, app.All, and so on all work on the returned value, exactly as app.get / app.use do in JavaScript. An *Application also satisfies http.Handler through ServeHTTP, so it can be handed to http.ListenAndServe, wrapped by other net/http middleware, or driven directly in tests with net/http/httptest. The convenience Listen and ListenWithServer helpers exist for the common serving cases, and WrapHandler / WrapHandlerFunc adapt any existing net/http handler into an express.Handler.

Handlers ¶

A handler has the type express.Handler, defined as func(req *Request, res *Response, next Next). Every handler receives the wrapped request, the wrapped response, and a Next function used to pass control down the stack. Calling next() continues to the next matching layer; calling next(err) diverts to error-handling middleware, which is any function with the ErrorHandler shape func(err error, req *Request, res *Response, next Next). Request exposes Express-style accessors — Params for captured route parameters, Query for query-string values, Get for headers, Body and the Parse helpers for payloads — while Response offers chainable writers such as Status, Set, Send, JSON, Redirect, and Cookie. This keeps handler code terse and reads much like its JavaScript counterpart.

Routing ¶

Routing follows Express's path syntax. Patterns support named parameters (":id"), optional parameters (":id?"), custom regular-expression constraints (":id(\\d+)"), and wildcards ("*"), all compiled into standard library regexp under the hood. Every HTTP verb has a method (Get, Post, Put, Delete, Patch, Head, Options, All), including Query for the emerging QUERY method. Routers are first-class: a Router created with NewRouter can register its own middleware and routes and then be mounted on the app (or another router) with app.Use("/prefix", subRouter), enabling modular, prefix-scoped route trees. RouterOptions mirrors Express's case-sensitive, strict, and merge-params toggles, and app.Param registers parameter-preprocessing callbacks that run once per request before the matched route.

Views, streaming, and settings ¶

View rendering is included as well. app.Engine registers a template engine for a file extension, res.Render resolves a view against the configured "views" directories and "view engine" setting and streams the rendered HTML, and a cache-aware html/template engine is wired up by default for ".html" and ".tmpl" files. For dynamic output, res.Stream writes chunked responses and res.SSE returns an SSEWriter for Server-Sent Events, while res.SendFile, res.Download, and res.Attachment cover static and downloadable content with conditional-request support. Application settings (Set, GetSetting, Enable, Disable, Enabled, Disabled) and per-request Locals round out the Express feature set, giving handlers a place to stash configuration and request-scoped data.

Batteries: middleware and utility ports ¶

Beyond the core framework, this module ships 191 importable packages in total. Under middleware/ live 102 connect-style middleware — body parsing, CORS, compression, sessions, rate limiting, security headers (helmet, CSP, HSTS), CSRF, and more — each exposed as express.Handler values. Alongside them sit 88 standalone utility packages (81 top-level plus the seven lodash/* subpackages) that port popular npm libraries such as accepts, cookie, content-type, content-disposition, bytes, ms, qs, jsonwebtoken, uuid, nanoid, and many others as ordinary, dependency-free Go packages. Each utility package documents the npm package it corresponds to and the parity it targets, so an Express codebase can be translated to Go piece by piece. The aim throughout is Express.js parity: familiar names, familiar semantics, and behavior that matches the Node originals closely enough to port real applications with minimal surprise.

Example ¶

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"))
Example ¶

Example builds a small but complete application and drives one request through it without opening a socket. It shows the pieces that make up an Express program in Go: express.New returns an *Application whose embedded Router exposes Use and the HTTP-method verbs directly, a Handler has the signature func(req, res, next), middleware runs before the matched route and calls next to continue, and because *Application implements http.Handler the whole app can be exercised with net/http/httptest by calling ServeHTTP. The route below captures a :name path parameter and echoes it back as JSON.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/malcolmston/express"
)

func main() {
	app := express.New()

	// Application-wide middleware: annotate every response, then continue.
	app.Use(func(req *express.Request, res *express.Response, next express.Next) {
		res.Set("X-App", "demo")
		next()
	})

	// A route with a named parameter, answering with JSON.
	app.Get("/hello/:name", func(req *express.Request, res *express.Response, next express.Next) {
		res.JSON(map[string]string{"hello": req.Params("name")})
	})

	// Drive a request through the app with httptest — no network needed.
	rec := httptest.NewRecorder()
	rec.Body.Reset()
	r := httptest.NewRequest(http.MethodGet, "/hello/world", nil)
	app.ServeHTTP(rec, r)

	fmt.Println("status:", rec.Code)
	fmt.Println("x-app:", rec.Header().Get("X-App"))
	fmt.Println("body:", strings.TrimSpace(rec.Body.String()))
}
Output:
status: 200
x-app: demo
body: {"hello":"world"}

Index ¶

Examples ¶

Constants ¶

View Source
const DefaultSessionCookie = "connect.sid"

DefaultSessionCookie is the cookie name used by the session middleware, matching the default used by Node's express-session.

View Source
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 New ¶

func New() *Application

New creates a new express Application.

func (*Application) AsyncAPI ¶ added in v0.4.0

func (app *Application) AsyncAPI() *AsyncAPIDoc

AsyncAPI builds an AsyncAPI 2.6 document from the channels registered with Application.Channel. The result can be served directly with res.JSON. When no channels are registered the document still validates, with an empty channels object.

func (*Application) Channel ¶ added in v0.4.0

func (app *Application) Channel(name string, doc ChannelDoc) *Application

Channel registers an event/message channel (for example a Socket.IO or WebSocket topic) that is included in the generated AsyncAPI document. It returns the app for chaining.

func (*Application) ChannelNames ¶ added in v0.4.0

func (app *Application) ChannelNames() []string

ChannelNames returns the registered channel names in sorted order.

func (*Application) Describe ¶ added in v0.4.0

func (app *Application) Describe(method, path string, doc RouteDoc) *Application

Describe attaches documentation metadata to the route identified by method and path (the same path string used to register it, e.g. "/users/:id"). It may be called before or after the route is registered and returns the app for chaining. Method is matched case-insensitively.

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) Docs ¶ added in v0.4.0

func (app *Application) Docs(opts ...DocsOptions) *Application

Docs enables automatic API documentation for the application. It generates an OpenAPI 3.1 specification from the registered routes (enriched by any Application.Describe calls), an AsyncAPI document from any Application.Channel calls, and a Postman collection, and mounts endpoints that serve them together with interactive Swagger UI and ReDoc pages.

The specifications are (re)built on each request, so routes registered after Docs still appear. Pass a DocsOptions to customise titles, servers and endpoint paths; the zero value uses the documented defaults:

app.Docs()                                  // defaults
app.Docs(express.DocsOptions{Title: "..."}) // customised

Docs returns the app for chaining.

Example ¶

ExampleApplication_Docs shows how a single call to app.Docs turns an application's registered routes into a live OpenAPI 3.1 specification (plus Swagger UI, ReDoc, a YAML spec, an AsyncAPI document for event channels and a Postman collection). Routes are introspected automatically; Describe adds the details introspection cannot infer, and Channel documents socket/event topics.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/malcolmston/express"
)

func main() {
	app := express.New()

	app.Get("/users/:id", func(req *express.Request, res *express.Response, next express.Next) {
		res.JSON(map[string]string{"id": req.Params("id")})
	})

	// Optional: enrich the generated operation.
	app.Describe("GET", "/users/:id", express.RouteDoc{
		Summary: "Fetch a user",
		Tags:    []string{"users"},
	})

	// Optional: document a socket/event channel for the AsyncAPI spec.
	app.Channel("chat.message", express.ChannelDoc{
		Subscribe: &express.MessageDoc{Name: "messageReceived"},
	})

	// Mount /docs, /openapi.json, /openapi.yaml, /redoc, /asyncapi.json and
	// /postman.json.
	app.Docs(express.DocsOptions{Title: "Users API", Version: "1.0.0"})

	rec := httptest.NewRecorder()
	app.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/openapi.json", nil))

	doc := app.OpenAPI()
	fmt.Println("openapi:", doc.OpenAPI)
	fmt.Println("title:", doc.Info.Title)
	fmt.Println("has /users/{id}:", doc.Paths["/users/{id}"] != nil)
	fmt.Println("served status:", rec.Code)
}
Output:
openapi: 3.1.0
title: Users API
has /users/{id}: true
served status: 200

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) OpenAPI ¶ added in v0.4.0

func (app *Application) OpenAPI() *OpenAPIDoc

OpenAPI builds an OpenAPI 3.1 document describing every route registered on the application. Routes contribute their method, templated path and path parameters automatically; any metadata attached with Application.Describe enriches the matching operation, and a DocsOptions.Enrich hook (if set) gets the final say. The returned value can be served directly with res.JSON.

func (*Application) OpenAPIYAML ¶ added in v0.4.0

func (app *Application) OpenAPIYAML() string

OpenAPIYAML returns the OpenAPI document rendered as YAML.

func (*Application) PostmanCollection ¶ added in v0.4.0

func (app *Application) PostmanCollection() *PostmanCollection

PostmanCollection builds a Postman Collection v2.1 from the registered routes. Path parameters are rendered in Postman's ":param" style. The {{baseUrl}} variable stands in for the server so the collection is host-agnostic.

func (*Application) Render ¶ added in v0.4.0

func (app *Application) Render(name string, data any) (string, error)

Render resolves a view name against the app's "views" directories and "view engine" setting, renders it with the matching engine, and returns the output. It is the app-level equivalent of Express's app.render.

func (*Application) Routes ¶ added in v0.4.0

func (app *Application) Routes() []RouteInfo

Routes returns every HTTP route registered on the application, including those contributed by mounted sub-routers (with their mount prefixes applied). Middleware layers (which match every method) are omitted; only method-bound routes are reported. The result is sorted by path then method and de-duplicated, so a route with several handlers appears once.

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 AsyncAPIChannel ¶ added in v0.4.0

type AsyncAPIChannel struct {
	Description string             `json:"description,omitempty"`
	Subscribe   *AsyncAPIOperation `json:"subscribe,omitempty"`
	Publish     *AsyncAPIOperation `json:"publish,omitempty"`
}

AsyncAPIChannel documents one channel with optional publish/subscribe operations.

type AsyncAPIDoc ¶ added in v0.4.0

type AsyncAPIDoc struct {
	AsyncAPI string                     `json:"asyncapi"`
	Info     OpenAPIInfo                `json:"info"`
	Servers  map[string]AsyncAPIServer  `json:"servers,omitempty"`
	Channels map[string]AsyncAPIChannel `json:"channels"`
}

AsyncAPIDoc is the root of a generated AsyncAPI 2.6 document describing the application's event channels. It marshals to canonical AsyncAPI JSON.

type AsyncAPIMessage ¶ added in v0.4.0

type AsyncAPIMessage struct {
	Name        string         `json:"name,omitempty"`
	Title       string         `json:"title,omitempty"`
	Summary     string         `json:"summary,omitempty"`
	ContentType string         `json:"contentType,omitempty"`
	Payload     map[string]any `json:"payload,omitempty"`
	Examples    []any          `json:"examples,omitempty"`
}

AsyncAPIMessage documents a channel message payload.

type AsyncAPIOperation ¶ added in v0.4.0

type AsyncAPIOperation struct {
	Message AsyncAPIMessage `json:"message"`
}

AsyncAPIOperation is a publish or subscribe operation carrying one message.

type AsyncAPIServer ¶ added in v0.4.0

type AsyncAPIServer struct {
	URL      string `json:"url"`
	Protocol string `json:"protocol"`
}

AsyncAPIServer is a single entry of the AsyncAPI servers block.

type BasicAuthOptions ¶ added in v0.4.0

type BasicAuthOptions struct {
	// Users maps usernames to passwords. Used when Validate is nil.
	Users map[string]string
	// Validate, when set, authenticates a (username, password) pair and takes
	// precedence over Users.
	Validate func(user, pass string) bool
	// Realm is the authentication realm sent in the challenge; defaults to
	// "Restricted".
	Realm string
}

BasicAuthOptions configures the BasicAuth middleware.

type BodyDoc ¶ added in v0.4.0

type BodyDoc struct {
	// Description explains the body.
	Description string
	// Required marks the body as mandatory.
	Required bool
	// ContentType is the media type; it defaults to "application/json".
	ContentType string
	// Schema is a JSON-Schema object describing the payload.
	Schema map[string]any
	// Example is an optional example value serialised alongside the schema.
	Example any
}

BodyDoc documents a request body.

type CORSOptions ¶ added in v0.4.0

type CORSOptions struct {
	// AllowOrigins is the list of allowed origins. An entry of "*" (or an empty
	// list) allows any origin. Otherwise the request's Origin is echoed back
	// only when it appears in the list.
	AllowOrigins []string
	// AllowMethods is the list of methods advertised on preflight. Defaults to
	// GET, HEAD, PUT, PATCH, POST and DELETE.
	AllowMethods []string
	// AllowHeaders is advertised on preflight; when empty the requested headers
	// are reflected.
	AllowHeaders []string
	// ExposeHeaders lists response headers browsers may read.
	ExposeHeaders []string
	// AllowCredentials sets Access-Control-Allow-Credentials.
	AllowCredentials bool
	// MaxAge is the preflight cache lifetime in seconds.
	MaxAge int
}

CORSOptions configures the CORS middleware. The zero value is valid and permits any origin with the common HTTP methods.

type ChannelDoc ¶ added in v0.4.0

type ChannelDoc struct {
	// Description explains the channel's purpose.
	Description string
	// Subscribe describes the message the server SENDS to subscribers on this
	// channel (what a client receives).
	Subscribe *MessageDoc
	// Publish describes the message clients SEND to the server on this channel
	// (what the server receives).
	Publish *MessageDoc
}

ChannelDoc documents a single event/message channel (for example a Socket.IO event, a WebSocket topic or a message-queue subject) for inclusion in the generated AsyncAPI document.

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 DocsOptions ¶ added in v0.4.0

type DocsOptions struct {
	// Title, Version and Description populate the spec's info block. Title
	// defaults to "API", Version to the app's "version" setting or "1.0.0".
	Title       string
	Version     string
	Description string
	// Servers are base URLs advertised in the OpenAPI servers block.
	Servers []string

	// UIPath serves the Swagger UI HTML page (default "/docs").
	UIPath string
	// RedocPath serves the ReDoc HTML page (default "/redoc").
	RedocPath string
	// OpenAPIPath serves the OpenAPI 3.1 document as JSON (default
	// "/openapi.json").
	OpenAPIPath string
	// OpenAPIYAMLPath serves the OpenAPI document as YAML (default
	// "/openapi.yaml").
	OpenAPIYAMLPath string
	// AsyncAPIPath serves the AsyncAPI 2.6 document as JSON (default
	// "/asyncapi.json"). Only meaningful when channels are registered.
	AsyncAPIPath string
	// PostmanPath serves a Postman v2.1 collection (default
	// "/postman.json").
	PostmanPath string

	// AssetBaseURL is the base URL for the Swagger UI / ReDoc browser assets.
	// It defaults to the jsDelivr CDN. Point it at a self-hosted copy for
	// offline use.
	AssetBaseURL string

	// Enrich, when set, is called for every operation as the OpenAPI document
	// is built, allowing programmatic customisation beyond Describe.
	Enrich func(route RouteInfo, op *Operation)
}

DocsOptions configures the documentation endpoints mounted by Application.Docs. The zero value is valid; every field has a sensible default. Set a *Path field to "-" to disable that individual endpoint (leaving it "" keeps the default).

type EngineFunc ¶

type EngineFunc func(path string, data any) (string, error)

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 ¶

type ErrorHandler func(err error, req *Request, res *Response, next Next)

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 ¶

type Handler func(req *Request, res *Response, next Next)

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 BasicAuth ¶ added in v0.4.0

func BasicAuth(opts BasicAuthOptions) Handler

BasicAuth returns middleware that enforces HTTP Basic authentication. It compares credentials in constant time when using the Users map, and responds with 401 and a WWW-Authenticate challenge when authentication fails.

func BodyLimit ¶ added in v0.4.0

func BodyLimit(maxBytes int64) Handler

BodyLimit returns middleware that rejects requests whose body exceeds maxBytes with 413 Payload Too Large, and caps reads of the body so a lying Content-Length cannot exhaust memory.

func CORS ¶ added in v0.4.0

func CORS(opts ...CORSOptions) Handler

CORS returns middleware that adds Cross-Origin Resource Sharing headers and answers preflight (OPTIONS) requests with 204, mirroring the popular Express cors middleware.

func Compose ¶ added in v0.4.0

func Compose(handlers ...Handler) Handler

Compose combines several handlers into a single Handler that runs them in order, each able to short-circuit by not calling next. It is handy for bundling a fixed middleware stack into one value.

func Compress ¶ added in v0.4.0

func Compress() Handler

Compress returns middleware that gzip-encodes the response body when the client advertises gzip support via Accept-Encoding. It sets Content-Encoding, varies on Accept-Encoding and removes any premature Content-Length.

func Favicon ¶ added in v0.4.0

func Favicon(path string) Handler

Favicon returns middleware that serves the icon at path for GET/HEAD requests to /favicon.ico (with a one-day cache), short-circuiting the rest of the stack. Other requests pass through.

func HealthCheck ¶ added in v0.4.0

func HealthCheck(path, body string) Handler

HealthCheck returns middleware that answers GET requests to path with 200 and the given body (or "OK" when empty), short-circuiting the stack — a ready-made liveness/readiness endpoint.

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 MethodOverride ¶ added in v0.4.0

func MethodOverride() Handler

MethodOverride returns middleware that lets a POST request masquerade as another method via the X-HTTP-Method-Override header or a `_method` query parameter — useful for HTML forms that cannot issue PUT/DELETE directly.

func Multipart ¶

func Multipart(maxMemory int64) Handler

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 NoCache ¶ added in v0.4.0

func NoCache() Handler

NoCache returns middleware that sets response headers instructing clients and proxies not to cache the response.

func RateLimit ¶ added in v0.4.0

func RateLimit(opts RateLimitOptions) Handler

RateLimit returns middleware implementing a fixed-window rate limiter keyed by client IP (or a custom key). It sets X-RateLimit-Limit/Remaining/Reset headers and answers 429 with a Retry-After header once the limit is exceeded.

func RealIP ¶ added in v0.4.0

func RealIP() Handler

RealIP returns middleware that rewrites the request's remote address from the X-Real-IP or the first X-Forwarded-For entry, so downstream code and req.IP observe the client address when running behind a trusted proxy.

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 RedirectToHTTPS ¶ added in v0.4.0

func RedirectToHTTPS() Handler

RedirectToHTTPS returns middleware that 301-redirects insecure requests to their https:// equivalent. Requests already served over TLS pass through.

func RequestID ¶ added in v0.4.0

func RequestID() Handler

RequestID returns middleware that ensures every request carries an X-Request-Id: it reuses an inbound one or generates a random 128-bit id, and echoes it on both the request and the response.

func ResponseTime ¶ added in v0.4.0

func ResponseTime() Handler

ResponseTime returns middleware that measures how long the downstream handlers take and sets the elapsed milliseconds on the X-Response-Time header just before the response is written.

func SecurityHeaders ¶ added in v0.4.0

func SecurityHeaders(opts ...SecurityOptions) Handler

SecurityHeaders returns middleware that sets a baseline of security-related response headers (X-Content-Type-Options, X-Frame-Options, Referrer-Policy and optionally Strict-Transport-Security and Content-Security-Policy), analogous to helmet for Express.

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 SetHeaders ¶ added in v0.4.0

func SetHeaders(headers map[string]string) Handler

SetHeaders returns middleware that sets a fixed set of response headers on every request.

func Static ¶

func Static(root string) Handler

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 Timeout ¶ added in v0.4.0

func Timeout(d time.Duration) Handler

Timeout returns middleware that attaches a deadline of d to the request context, so downstream handlers that honour req.Raw.Context() abort when the deadline elapses.

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 When ¶ added in v0.4.0

func When(pred func(*Request) bool, h Handler) Handler

When returns middleware that runs h only when pred reports true for the request; otherwise it passes straight through.

func WrapHandler ¶

func WrapHandler(h http.Handler) Handler

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)

Destroy removes the session stored under id, if any.

func (*MemorySessionStore) Get ¶

func (m *MemorySessionStore) Get(id string) (map[string]any, bool)

Get returns a copy of the session data for id and whether it was present.

func (*MemorySessionStore) Set ¶

func (m *MemorySessionStore) Set(id string, data map[string]any)

Set stores a copy of data under id, overwriting any existing session.

type MessageDoc ¶ added in v0.4.0

type MessageDoc struct {
	// Name is a machine-friendly message name.
	Name string
	// Title is a human-friendly message title.
	Title string
	// Summary is a short explanation of the message.
	Summary string
	// ContentType is the payload media type; defaults to "application/json".
	ContentType string
	// Payload is a JSON-Schema object describing the message body.
	Payload map[string]any
	// Example is an optional example payload.
	Example any
}

MessageDoc documents the payload of a channel message.

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 OpenAPIDoc ¶ added in v0.4.0

type OpenAPIDoc struct {
	OpenAPI string                           `json:"openapi"`
	Info    OpenAPIInfo                      `json:"info"`
	Servers []OpenAPIServer                  `json:"servers,omitempty"`
	Tags    []OpenAPITag                     `json:"tags,omitempty"`
	Paths   map[string]map[string]*Operation `json:"paths"`
}

OpenAPIDoc is the root of a generated OpenAPI 3.1 document. It marshals to the canonical OpenAPI JSON shape and can be served directly with res.JSON.

type OpenAPIInfo ¶ added in v0.4.0

type OpenAPIInfo struct {
	Title       string `json:"title"`
	Version     string `json:"version"`
	Description string `json:"description,omitempty"`
}

OpenAPIInfo is the info block of an OpenAPI document.

type OpenAPIMediaType ¶ added in v0.4.0

type OpenAPIMediaType struct {
	Schema  map[string]any `json:"schema,omitempty"`
	Example any            `json:"example,omitempty"`
}

OpenAPIMediaType is a schema/example pair keyed by media type in content maps.

type OpenAPIParam ¶ added in v0.4.0

type OpenAPIParam struct {
	Name        string         `json:"name"`
	In          string         `json:"in"`
	Description string         `json:"description,omitempty"`
	Required    bool           `json:"required,omitempty"`
	Schema      map[string]any `json:"schema,omitempty"`
}

OpenAPIParam is a single operation parameter.

type OpenAPIRequestBody ¶ added in v0.4.0

type OpenAPIRequestBody struct {
	Description string                      `json:"description,omitempty"`
	Required    bool                        `json:"required,omitempty"`
	Content     map[string]OpenAPIMediaType `json:"content"`
}

OpenAPIRequestBody documents an operation's request body.

type OpenAPIResponse ¶ added in v0.4.0

type OpenAPIResponse struct {
	Description string                      `json:"description"`
	Content     map[string]OpenAPIMediaType `json:"content,omitempty"`
}

OpenAPIResponse documents a single response.

type OpenAPIServer ¶ added in v0.4.0

type OpenAPIServer struct {
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
}

OpenAPIServer is a single entry of the OpenAPI servers block.

type OpenAPITag ¶ added in v0.4.0

type OpenAPITag struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

OpenAPITag documents a tag used to group operations.

type Operation ¶ added in v0.4.0

type Operation struct {
	Tags        []string                   `json:"tags,omitempty"`
	Summary     string                     `json:"summary,omitempty"`
	Description string                     `json:"description,omitempty"`
	OperationID string                     `json:"operationId,omitempty"`
	Deprecated  bool                       `json:"deprecated,omitempty"`
	Parameters  []OpenAPIParam             `json:"parameters,omitempty"`
	RequestBody *OpenAPIRequestBody        `json:"requestBody,omitempty"`
	Responses   map[string]OpenAPIResponse `json:"responses"`
}

Operation is a single OpenAPI operation (one method on one path). It is exposed so the DocsOptions.Enrich hook can customise generated operations.

type ParamDoc ¶ added in v0.4.0

type ParamDoc struct {
	// Name is the parameter name.
	Name string
	// In is the parameter location: "query", "header", "path" or "cookie".
	In string
	// Description explains the parameter.
	Description string
	// Required marks the parameter as mandatory. Path parameters are always
	// required regardless of this field.
	Required bool
	// Schema is a JSON-Schema object for the parameter's value. When nil a
	// permissive {"type":"string"} schema is used.
	Schema map[string]any
}

ParamDoc documents a single operation parameter.

type ParamHandler ¶

type ParamHandler func(req *Request, res *Response, next Next, value string)

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 PostmanCollection ¶ added in v0.4.0

type PostmanCollection struct {
	Info PostmanInfo   `json:"info"`
	Item []PostmanItem `json:"item"`
}

PostmanCollection is a minimal Postman Collection v2.1 document generated from the application's routes. It marshals to a file importable by Postman/Insomnia.

type PostmanInfo ¶ added in v0.4.0

type PostmanInfo struct {
	Name   string `json:"name"`
	Schema string `json:"schema"`
}

PostmanInfo is the info block of a Postman collection.

type PostmanItem ¶ added in v0.4.0

type PostmanItem struct {
	Name    string         `json:"name"`
	Request PostmanRequest `json:"request"`
}

PostmanItem is a single request entry in a Postman collection.

type PostmanRequest ¶ added in v0.4.0

type PostmanRequest struct {
	Method string     `json:"method"`
	Header []any      `json:"header"`
	URL    PostmanURL `json:"url"`
}

PostmanRequest describes the HTTP request of a Postman item.

type PostmanURL ¶ added in v0.4.0

type PostmanURL struct {
	Raw  string   `json:"raw"`
	Host []string `json:"host"`
	Path []string `json:"path"`
}

PostmanURL is the structured URL of a Postman request.

type Range ¶

type Range struct {
	Start int64
	End   int64 // inclusive
}

Range represents a single byte range parsed from a Range header.

type RateLimitOptions ¶ added in v0.4.0

type RateLimitOptions struct {
	// Max is the maximum number of requests per key per window. Defaults to 60.
	Max int
	// Window is the length of the fixed rate-limiting window. Defaults to one
	// minute.
	Window time.Duration
	// KeyFunc derives the rate-limit bucket key from a request; defaults to the
	// client IP.
	KeyFunc func(*Request) string
	// Message is the 429 response body; defaults to "Too Many Requests".
	Message string
}

RateLimitOptions configures the RateLimit middleware.

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 ¶

func (req *Request) Accepts(offers ...string) string

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 ¶

func (req *Request) AcceptsCharsets(offers ...string) string

AcceptsCharsets returns the best match among the offered charsets for the Accept-Charset header, or "".

func (*Request) AcceptsEncodings ¶

func (req *Request) AcceptsEncodings(offers ...string) string

AcceptsEncodings returns the best match among the offered encodings for the Accept-Encoding header, or "".

func (*Request) AcceptsLanguages ¶

func (req *Request) AcceptsLanguages(offers ...string) string

AcceptsLanguages returns the best match among the offered languages for the Accept-Language header, or "".

func (*Request) AllParams ¶

func (req *Request) AllParams() map[string]string

AllParams returns all captured route parameters.

func (*Request) BaseURL ¶ added in v0.4.0

func (req *Request) BaseURL() string

BaseURL returns the scheme and host portion of the request, e.g. "https://example.com", without a trailing slash.

func (*Request) Body ¶

func (req *Request) Body() any

Body returns the parsed request body. Call one of the Parse* helpers or the body-parser middleware first; otherwise it returns nil.

func (*Request) BodyJSON ¶

func (req *Request) BodyJSON(dst any) error

BodyJSON reads and unmarshals a JSON request body into dst.

func (*Request) ContentType ¶ added in v0.4.0

func (req *Request) ContentType() string

ContentType returns the request's Content-Type without any parameters (e.g. "application/json" for "application/json; charset=utf-8").

func (*Request) Cookie ¶

func (req *Request) Cookie(name string) string

Cookie returns the value of a named cookie, or "" if not present.

func (*Request) Files ¶

func (req *Request) Files(name string) []*multipart.FileHeader

Files returns all uploaded file headers for a form field.

func (*Request) Form ¶

func (req *Request) Form() url.Values

Form parses and returns all form values (query + body) as url.Values.

func (*Request) FormFile ¶

func (req *Request) FormFile(name string) (multipart.File, *multipart.FileHeader, error)

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) FormValue ¶

func (req *Request) FormValue(name string) string

FormValue parses form data (query + body) and returns a single value.

func (*Request) Fresh ¶

func (req *Request) Fresh(res *Response) bool

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) Get ¶

func (req *Request) Get(field string) string

Get returns a request header value (case-insensitive), Express's req.get.

func (*Request) Header ¶

func (req *Request) Header(field string) string

Header is an alias for Get.

func (*Request) Hostname ¶

func (req *Request) Hostname() string

Hostname returns the host portion of the request, honoring the Host header.

func (*Request) IP ¶

func (req *Request) IP() string

IP returns the remote address of the request.

func (*Request) Is ¶

func (req *Request) Is(typ string) bool

Is reports whether the request's Content-Type matches the given type, e.g. req.Is("json") or req.Is("text/html").

func (*Request) Method ¶

func (req *Request) Method() string

Method returns the request's HTTP method (GET, POST, ...).

func (*Request) OriginalURL ¶

func (req *Request) OriginalURL() string

OriginalURL returns the full request URI as received.

func (*Request) Params ¶

func (req *Request) Params(name string) string

Params returns a captured route parameter by name, or "" if absent.

func (*Request) Path ¶

func (req *Request) Path() string

Path returns the request URL path (without query string).

func (*Request) Protocol ¶

func (req *Request) Protocol() string

Protocol returns "https" when the request arrived over TLS, else "http".

func (*Request) Query ¶

func (req *Request) Query(name string) string

Query returns the first value of a query-string parameter.

func (*Request) QueryValues ¶

func (req *Request) QueryValues() url.Values

QueryValues returns the parsed query string as url.Values.

func (*Request) Ranges ¶

func (req *Request) Ranges(size int64) ([]Range, bool)

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) Referrer ¶ added in v0.4.0

func (req *Request) Referrer() string

Referrer returns the request's referrer URL, accepting either the correctly spelled "Referer" header or the "Referrer" variant.

func (*Request) Secure ¶

func (req *Request) Secure() bool

Secure reports whether the request was made over a secure connection.

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) Set ¶

func (req *Request) Set(key string, value any)

Set stores an arbitrary value on the request for downstream handlers.

func (*Request) SetBody ¶

func (req *Request) SetBody(v any)

SetBody stores a parsed body value (used by body-parsing middleware).

func (*Request) SetPath ¶

func (req *Request) SetPath(p string)

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.

func (*Request) Stale ¶

func (req *Request) Stale(res *Response) bool

Stale is the negation of Fresh.

func (*Request) Subdomains ¶ added in v0.4.0

func (req *Request) Subdomains(offset ...int) []string

Subdomains returns the subdomain labels of the request Host in reverse order, excluding the last `offset` labels (default 2 — the domain and TLD). For "tobi.ferrets.example.com" it returns ["ferrets", "tobi"]. It mirrors Express's req.subdomains.

func (*Request) UserAgent ¶ added in v0.4.0

func (req *Request) UserAgent() string

UserAgent returns the request's User-Agent header.

func (*Request) Value ¶

func (req *Request) Value(key string) (any, bool)

Value retrieves a value previously stored with Set.

func (*Request) Xhr ¶ added in v0.4.0

func (req *Request) Xhr() bool

Xhr reports whether the request was made with an XMLHttpRequest, detected via the X-Requested-With header (case-insensitive), mirroring Express's req.xhr.

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) Append ¶

func (res *Response) Append(field, value string) *Response

Append adds a value to an existing response header without replacing it.

func (*Response) Attachment ¶

func (res *Response) Attachment(filename ...string) *Response

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) CacheControl ¶ added in v0.4.0

func (res *Response) CacheControl(directive string) *Response

CacheControl sets the Cache-Control response header to directive and returns res for chaining.

func (*Response) ClearCookie ¶

func (res *Response) ClearCookie(name string) *Response

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 ¶

func (res *Response) Download(path string, filename ...string) error

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 ¶

func (res *Response) ETag(tag string) *Response

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 ¶

func (res *Response) Flush() bool

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 ¶

func (res *Response) Format(handlers map[string]func())

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 ¶

func (res *Response) Fresh() bool

Fresh reports whether the current request is fresh against the headers set on this response (convenience wrapper around req.Fresh).

func (*Response) GetHeader ¶

func (res *Response) GetHeader(field string) string

GetHeader returns a header value already set on the response.

func (*Response) JSON ¶

func (res *Response) JSON(v any) *Response

JSON serializes v as JSON and writes it with an application/json Content-Type.

func (*Response) JSONP ¶ added in v0.4.0

func (res *Response) JSONP(v any) *Response

JSONP sends a JSONP response: the value v serialised as JSON and wrapped in a call to the callback function named by the request's query parameter (default "callback"). When no callback parameter is present it falls back to a normal JSON response. The body is prefixed with `/**/` and the content type is set to application/javascript, mirroring Express's res.jsonp.

func (*Response) LastModified ¶

func (res *Response) LastModified(t time.Time) *Response

LastModified sets the Last-Modified header from t.

func (res *Response) Links(links map[string]string) *Response

Links sets the Link response header from a map of rel -> URL, as in Express's res.links. For example {"next": "http://…?page=2"} becomes `<http://…?page=2>; rel="next"`.

func (*Response) Location ¶

func (res *Response) Location(url string) *Response

Location sets the Location response header.

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 ¶

func (res *Response) Redirect(args ...any) *Response

Redirect sends a redirect response. If a status code is provided it is used; otherwise 302 Found is assumed.

func (*Response) RemoveHeader ¶ added in v0.4.0

func (res *Response) RemoveHeader(field string) *Response

RemoveHeader deletes the named response header and returns res for chaining.

func (*Response) Render ¶

func (res *Response) Render(name string, data ...any) error

Render renders a view and sends it as HTML. The view name is resolved against the app's "views" directories and "view engine" setting. When data is a map[string]any it is layered over res.Locals (so per-render values win while app/request locals remain visible); any other value is passed through as-is. When data is omitted, res.Locals is used.

func (*Response) SSE ¶

func (res *Response) SSE() *SSEWriter

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 ¶

func (res *Response) Send(body any) *Response

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 ¶

func (res *Response) SendChunked(data []byte, chunkSize int) error

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 ¶

func (res *Response) SendFile(path string) error

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 ¶

func (res *Response) SendStatus(code int) *Response

SendStatus sets the status code and sends its standard text as the body.

func (*Response) SendStream ¶

func (res *Response) SendStream(r io.Reader, chunkSize ...int) error

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) Set ¶

func (res *Response) Set(field, value string) *Response

Set assigns a response header, returning the response for chaining.

func (*Response) Status ¶

func (res *Response) Status(code int) *Response

Status sets the HTTP status code and returns the response for chaining.

func (*Response) StatusCode ¶

func (res *Response) StatusCode() int

StatusCode returns the currently set status code.

func (*Response) Stream ¶

func (res *Response) Stream(fn func(w io.Writer) error) error

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 ¶

func (res *Response) Type(t string) *Response

Type sets the Content-Type header. Common shorthands ("json", "html", "text") are expanded; anything containing a slash is used verbatim.

func (*Response) Vary ¶

func (res *Response) Vary(field string) *Response

Vary adds a field to the Vary response header.

func (*Response) Write ¶

func (res *Response) Write(p []byte) (int, error)

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 ¶

func (res *Response) WriteChunk(p []byte) (int, error)

WriteChunk writes a chunk and immediately flushes it to the client — the building block for chunked streaming responses.

func (*Response) WriteString ¶

func (res *Response) WriteString(s string) (int, error)

WriteString writes a string chunk (without flushing).

func (*Response) Written ¶

func (res *Response) Written() bool

Written reports whether the response headers have been committed.

type ResponseDoc ¶ added in v0.4.0

type ResponseDoc struct {
	// Description explains the response; OpenAPI requires it to be non-empty,
	// so a default is substituted when blank.
	Description string
	// ContentType is the media type of the body; defaults to
	// "application/json" when a Schema or Example is present.
	ContentType string
	// Schema is a JSON-Schema object describing the response body.
	Schema map[string]any
	// Example is an optional example value.
	Example any
}

ResponseDoc documents a single response.

type Route ¶

type Route struct {
	// contains filtered or unexported fields
}

Route binds handlers for multiple HTTP methods to a single path.

func (*Route) All ¶

func (rt *Route) All(h ...Handler) *Route

All registers handlers for every method on the route.

func (*Route) Delete ¶

func (rt *Route) Delete(h ...Handler) *Route

Delete registers DELETE handlers on the route.

func (*Route) Get ¶

func (rt *Route) Get(h ...Handler) *Route

Get registers GET handlers on the route.

func (*Route) Patch ¶

func (rt *Route) Patch(h ...Handler) *Route

Patch registers PATCH handlers on the route.

func (*Route) Post ¶

func (rt *Route) Post(h ...Handler) *Route

Post registers POST handlers on the route.

func (*Route) Put ¶

func (rt *Route) Put(h ...Handler) *Route

Put registers PUT handlers on the route.

type RouteDoc ¶ added in v0.4.0

type RouteDoc struct {
	// Summary is a short one-line description of the operation.
	Summary string
	// Description is a longer explanation (CommonMark is allowed by OpenAPI).
	Description string
	// Tags group related operations in the UI.
	Tags []string
	// OperationID is a unique, machine-friendly identifier for the operation.
	OperationID string
	// Deprecated marks the operation as deprecated.
	Deprecated bool
	// Parameters describes query, header, cookie (and extra path) parameters.
	// Path parameters discovered from the route are added automatically and
	// need not be repeated here.
	Parameters []ParamDoc
	// RequestBody documents the request payload, if any.
	RequestBody *BodyDoc
	// Responses maps a status code (e.g. "200") or "default" to a response.
	// When empty, a generic 200 response is generated.
	Responses map[string]ResponseDoc
}

RouteDoc carries optional, human-authored metadata for a single route that enriches the generated OpenAPI operation beyond what introspection alone can infer (which is just the method, path and path parameters).

type RouteInfo ¶ added in v0.4.0

type RouteInfo struct {
	// Method is the upper-case HTTP method, e.g. "GET" or "POST".
	Method string
	// Path is the Express-style path pattern as registered, e.g.
	// "/users/:id". Use [RouteInfo.OpenAPIPath] for the templated form.
	Path string
	// Params are the path parameter names in order of appearance.
	Params []string
}

RouteInfo describes a single HTTP route discovered by introspecting an application's router tree. It is the raw material from which the OpenAPI, Postman and other specifications are generated.

func (RouteInfo) OpenAPIPath ¶ added in v0.4.0

func (ri RouteInfo) OpenAPIPath() string

OpenAPIPath returns Path with Express-style parameters (":id") rewritten to OpenAPI/URI-template form ("{id}") and the wildcard "*" rewritten to "{wildcard}", so the value is a valid OpenAPI path key.

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) All ¶

func (r *Router) All(path string, handlers ...Handler) *Router

All registers handlers that run for every HTTP method matching path.

func (*Router) Delete ¶

func (r *Router) Delete(path string, handlers ...Handler) *Router

Delete registers handlers for DELETE requests to path.

func (*Router) Get ¶

func (r *Router) Get(path string, handlers ...Handler) *Router

Get registers handlers for GET requests to path.

func (*Router) Head ¶

func (r *Router) Head(path string, handlers ...Handler) *Router

Head registers handlers for HEAD requests to path.

func (*Router) Options ¶

func (r *Router) Options(path string, handlers ...Handler) *Router

Options registers handlers for OPTIONS requests to path.

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) Patch ¶

func (r *Router) Patch(path string, handlers ...Handler) *Router

Patch registers handlers for PATCH requests to path.

func (*Router) Post ¶

func (r *Router) Post(path string, handlers ...Handler) *Router

Post registers handlers for POST requests to path.

func (*Router) Put ¶

func (r *Router) Put(path string, handlers ...Handler) *Router

Put registers handlers for PUT requests to path.

func (*Router) Query ¶

func (r *Router) Query(path string, handlers ...Handler) *Router

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 ¶

func (r *Router) Route(path string) *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) Routes ¶ added in v0.4.0

func (r *Router) Routes() []RouteInfo

Routes returns every HTTP route registered on the router (and its mounted sub-routers), sorted and de-duplicated. It is the router-level counterpart of Application.Routes.

func (*Router) Use ¶

func (r *Router) Use(args ...any) *Router

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 ¶

func (s *SSEWriter) Comment(text string) error

Comment emits an SSE comment line (often used as a keep-alive heartbeat).

func (*SSEWriter) Retry ¶

func (s *SSEWriter) Retry(ms int) error

Retry tells the client how long (in ms) to wait before reconnecting.

func (*SSEWriter) Send ¶

func (s *SSEWriter) Send(event, data string) error

Send emits a named event with a data payload. Multi-line data is split into multiple data: lines per the SSE spec.

func (*SSEWriter) SendData ¶

func (s *SSEWriter) SendData(data string) error

SendData emits an unnamed (message) event carrying data.

func (*SSEWriter) SendID ¶

func (s *SSEWriter) SendID(id, event, data string) error

SendID emits an event that also sets the SSE id field (for Last-Event-ID resumption).

func (*SSEWriter) SendJSON ¶

func (s *SSEWriter) SendJSON(event string, v any) error

SendJSON marshals v to JSON and emits it as a named event.

type SecurityOptions ¶ added in v0.4.0

type SecurityOptions struct {
	// ContentSecurityPolicy sets Content-Security-Policy. Empty leaves it unset;
	// use "-" to explicitly omit it.
	ContentSecurityPolicy string
	// FrameOptions sets X-Frame-Options; defaults to "SAMEORIGIN". Use "-" to
	// omit.
	FrameOptions string
	// HSTSMaxAge, when > 0, sets Strict-Transport-Security with that max-age.
	HSTSMaxAge int
	// ReferrerPolicy sets Referrer-Policy; defaults to "no-referrer". Use "-" to
	// omit.
	ReferrerPolicy string
	// DisableNoSniff omits the X-Content-Type-Options: nosniff header (set by
	// default).
	DisableNoSniff bool
}

SecurityOptions configures the SecurityHeaders middleware. The zero value applies sensible, helmet-like defaults.

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.

type SessionStore ¶

type SessionStore interface {
	Get(id string) (map[string]any, bool)
	Set(id string, data map[string]any)
	Destroy(id string)
}

SessionStore persists session data keyed by an opaque id. Implementations must be safe for concurrent use.

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 ansi is a standard-library-only Go port of the popular npm terminal styling library chalk (https://www.npmjs.com/package/chalk), which Node CLIs and Express dev tooling use to colour and format terminal output.
Package ansi is a standard-library-only Go port of the popular npm terminal styling library chalk (https://www.npmjs.com/package/chalk), which Node CLIs and Express dev tooling use to colour and format terminal output.
Package base32 encodes and decodes byte data using the RFC 4648 base32 alphabet, providing a small convenience wrapper over the standard library's encoding/base32.
Package base32 encodes and decodes byte data using the RFC 4648 base32 alphabet, providing a small convenience wrapper over the standard library's encoding/base32.
Package base58 is a standard-library-only Go implementation of Base58 and Base58Check encoding, the compact, ambiguity-free binary-to-text encoding popularised by Bitcoin and used across the npm ecosystem (bs58, base58check, bs58check) for keys, addresses and short identifiers.
Package base58 is a standard-library-only Go implementation of Base58 and Base58Check encoding, the compact, ambiguity-free binary-to-text encoding popularised by Bitcoin and used across the npm ecosystem (bs58, base58check, bs58check) for keys, addresses and short identifiers.
Package base62 is a standard-library-only Go implementation of Base62 encoding, the alphanumeric (0-9, A-Z, a-z) binary-to-text scheme used by URL shorteners and short-id generators across the npm ecosystem (base62, base-x).
Package base62 is a standard-library-only Go implementation of Base62 encoding, the alphanumeric (0-9, A-Z, a-z) binary-to-text scheme used by URL shorteners and short-id generators across the npm ecosystem (base62, base-x).
Package base64url encodes and decodes byte data using the RFC 4648 url-safe base64 alphabet without padding, as used in JWTs and other web tokens.
Package base64url encodes and decodes byte data using the RFC 4648 url-safe base64 alphabet without padding, as used in JWTs and other web tokens.
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 that Express-adjacent tooling uses to normalize option keys, identifiers, and header-derived names.
Package camelcase converts dash/dot/underscore/space separated (and mixed-case) strings into camelCase or PascalCase, modeled on the npm "camelcase" package that Express-adjacent tooling uses to normalize option keys, identifiers, and header-derived names.
Package changecase is a standard-library-only Go port of the popular npm package change-case (https://www.npmjs.com/package/change-case), which converts identifiers and phrases between the many casing conventions used in code and configuration.
Package changecase is a standard-library-only Go port of the popular npm package change-case (https://www.npmjs.com/package/change-case), which converts identifiers and phrases between the many casing conventions used in code and configuration.
Package chunk provides a faithful port of lodash's `chunk` utility using only the Go standard library.
Package chunk provides a faithful port of lodash's `chunk` utility using only the Go standard library.
Package color is a standard-library-only Go port of the color primitives that underpin the popular npm packages color-convert, tinycolor2 and chroma-js, which Express/Node web apps reach for when generating themes, badges and UI palettes.
Package color is a standard-library-only Go port of the color primitives that underpin the popular npm packages color-convert, tinycolor2 and chroma-js, which Express/Node web apps reach for when generating themes, badges and UI palettes.
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 using only the Go standard library.
Package contentrange formats and parses HTTP Content-Range header values using only the Go standard library.
Package contenttype parses and formats HTTP Content-Type header values, modeled on the npm "content-type" package and RFC 7231, using only the Go standard library.
Package contenttype parses and formats HTTP Content-Type header values, modeled on the npm "content-type" package and RFC 7231, using only the Go standard library.
Package cookie parses and serializes HTTP cookie headers, a port of the npm "cookie" package that Express and cookie-parser use to read the Cookie request header and to build Set-Cookie response headers.
Package cookie parses and serializes HTTP cookie headers, a port of the npm "cookie" package that Express and cookie-parser use to read the Cookie request header and to build Set-Cookie response 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 cuid generates collision-resistant unique identifiers, a Go port of the npm "cuid" package (in the style of its cuid2 successor).
Package cuid generates collision-resistant unique identifiers, a Go port of the npm "cuid" package (in the style of its cuid2 successor).
Package debounce provides a faithful port of lodash's debounce utility, built on only the Go standard library.
Package debounce provides a faithful port of lodash's debounce utility, built on only the Go standard library.
Package deburr provides a faithful port of lodash's deburr utility, built on only the Go standard library.
Package deburr provides a faithful port of lodash's deburr utility, built on only the Go standard library.
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, using only the Go standard 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, using only the Go standard library.
Package encodeurl encodes a URL to a percent-encoded form while leaving any already-encoded sequences intact, a port of the npm "encodeurl" package that Express and the send/serve-static middleware use when reflecting a request path back into a header such as Location.
Package encodeurl encodes a URL to a percent-encoded form while leaving any already-encoded sequences intact, a port of the npm "encodeurl" package that Express and the send/serve-static middleware use when reflecting a request path back into a header such as Location.
Package escapehtml escapes the HTML-significant characters in a string so it can be safely embedded in HTML markup, a port of the npm "escape-html" package that Express uses when rendering error pages and other user-influenced text.
Package escapehtml escapes the HTML-significant characters in a string so it can be safely embedded in HTML markup, a port of the npm "escape-html" package that Express uses when rendering error pages and other user-influenced text.
Package escaperegexp escapes regular-expression metacharacters in a string so the string can be embedded as a literal inside a larger pattern.
Package escaperegexp escapes regular-expression metacharacters in a string so the string can be embedded as a literal inside a larger pattern.
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, a faithful port of the npm package "filesize".
Package filesize converts a number of bytes into a human readable string, a faithful port of the npm package "filesize".
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), mirroring the popular npm "hashids" package.
Package hashids is a standard-library port of the Hashids algorithm (https://hashids.org), mirroring the popular npm "hashids" package.
Package hotp implements HMAC-based one-time passwords as defined in RFC 4226, used for counter-based two-factor authentication codes.
Package hotp implements HMAC-based one-time passwords as defined in RFC 4226, used for counter-based two-factor authentication codes.
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, the module used internally by Express and Koa to build the errors that middleware turns into HTTP responses.
Package httperrors provides an HTTP-aware error type modeled on the npm "http-errors" package, the module used internally by Express and Koa to build the errors that middleware turns into HTTP responses.
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 jsonwebtoken signs and verifies JSON Web Tokens (JWTs) using HMAC (HS256/HS384/HS512).
Package jsonwebtoken signs and verifies JSON Web Tokens (JWTs) using HMAC (HS256/HS384/HS512).
Package jwtdecode decodes the payload of a JSON Web Token without verifying its signature.
Package jwtdecode decodes the payload of a JSON Web Token without verifying its signature.
Package kebabcase converts strings to kebab-case, a stdlib-only Go port of the npm "kebab-case" package (which is itself commonly interchanged with lodash.kebabcase).
Package kebabcase converts strings to kebab-case, a stdlib-only Go port of the npm "kebab-case" package (which is itself commonly interchanged with lodash.kebabcase).
Package keygrip provides signing and verification of data using a rotating list of secret keys, a stdlib-only Go port of the npm "keygrip" library used by frameworks such as Express and Koa to protect signed cookies and other tamper-evident tokens.
Package keygrip provides signing and verification of data using a rotating list of secret keys, a stdlib-only Go port of the npm "keygrip" library used by frameworks such as Express and Koa to protect signed cookies and other tamper-evident tokens.
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" category of functions (https://lodash.com/docs - _.countBy, _.groupBy, _.keyBy, _.partition, _.map, _.filter, _.reduce, _.sortBy, _.orderBy, _.sample, _.shuffle and friends) to Go generics.
Package collection is a standalone, dependency-free port of lodash's "Collection" category of functions (https://lodash.com/docs - _.countBy, _.groupBy, _.keyBy, _.partition, _.map, _.filter, _.reduce, _.sortBy, _.orderBy, _.sample, _.shuffle and friends) to Go generics.
datefns
Package datefns ports the most commonly used helpers from the npm package date-fns (https://date-fns.org) to Go's standard time.Time.
Package datefns ports the most commonly used helpers from the npm package date-fns (https://date-fns.org) to Go's standard time.Time.
function
Package function provides idiomatic, generic Go ports of lodash's "Function" category (https://lodash.com/docs — after, before, negate, memoize, flip, wrap, over, overEvery, overSome, flow, flowRight, curry and partial).
Package function provides idiomatic, generic Go ports of lodash's "Function" category (https://lodash.com/docs — after, before, negate, memoize, flip, wrap, over, overEvery, overSome, flow, flowRight, curry and partial).
lang
Package lang ports the "Lang" category of the npm lodash library, together with a handful of closely related utility helpers, to idiomatic Go using only the standard library.
Package lang ports the "Lang" category of the npm lodash library, together with a handful of closely related utility helpers, to idiomatic Go using only the standard library.
math
Package math ports the "Math" and "Number" category functions of the npm lodash library to Go, implemented with generics and depending only on the standard library.
Package math ports the "Math" and "Number" category functions of the npm lodash library to Go, implemented with generics and depending only on the standard library.
object
Package object ports the "Object" category of the npm lodash library to Go, providing the map- and structure-oriented helpers such as Keys, Values, Entries, Pick, Omit, MapKeys, MapValues, Invert, Assign, Merge, Defaults, Get, Set, Has, Unset, Update, Clone, CloneDeep, IsEqual and Transform.
Package object ports the "Object" category of the npm lodash library to Go, providing the map- and structure-oriented helpers such as Keys, Values, Entries, Pick, Omit, MapKeys, MapValues, Invert, Assign, Merge, Defaults, Get, Set, Has, Unset, Update, Clone, CloneDeep, IsEqual and Transform.
str
Package str ports the "String" category of the npm lodash library to Go.
Package str ports the "String" category of the npm lodash library to Go.
util
Package util ports helpers from lodash's "Util" category (cond, stubArray, stubTrue/False/String, toPath and a stepped range) to idiomatic, generic Go.
Package util ports helpers from lodash's "Util" category (cond, stubArray, stubTrue/False/String, toPath and a stepped range) to idiomatic, generic Go.
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 and persists the assignment in a cookie so a returning visitor stays in the same bucket across requests.
Package abtest provides middleware that assigns each visitor a stable A/B test bucket and persists the assignment in a cookie so a returning visitor stays in the same bucket across requests.
acceptlanguage
Package acceptlanguage provides middleware that parses the Accept-Language request header, optionally negotiates it 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 it 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 (for example behind a reverse proxy at "/app") to be written as though it were served from root.
Package basepath provides middleware that strips a fixed prefix from the request path, allowing an application mounted under a sub-path (for example behind a reverse proxy at "/app") to be written as though it were served from root.
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 response bodies for clients that advertise gzip support via the Accept-Encoding request header.
Package compression provides express middleware that gzip-compresses response bodies for clients that advertise gzip support via the Accept-Encoding request header.
concurrencylimit
Package concurrencylimit provides express middleware that caps the number of requests processed concurrently and sheds load once that cap is reached.
Package concurrencylimit provides express middleware that caps the number of requests processed concurrently and sheds load once that cap is reached.
contenttypedefault
Package contenttypedefault provides express middleware that sets a fallback Content-Type on the response when a downstream handler does not set one itself.
Package contenttypedefault provides express middleware that sets a fallback Content-Type on the response when a downstream handler does not set one itself.
cookieparser
Package cookieparser provides express middleware that parses every cookie from the incoming request into a map[string]string and stores it on the request for convenient downstream access.
Package cookieparser provides express middleware that parses every cookie 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 as express middleware.
Package cookiesession implements a lightweight, cookie-only session store as express middleware.
correlationid
Package correlationid provides express middleware that assigns a correlation id to every request so that a single logical operation can be traced as it fans out across multiple services and log streams.
Package correlationid provides express middleware that assigns a correlation id to every request so that a single logical operation can be traced as it fans out across multiple services and log streams.
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 express middleware that sets the Cross-Origin-Embedder-Policy (COEP) response header on every response.
Package crossoriginembedder provides express middleware that sets the Cross-Origin-Embedder-Policy (COEP) response header on every response.
crossoriginopener
Package crossoriginopener provides express middleware that sets the Cross-Origin-Opener-Policy (COOP) response header on every response.
Package crossoriginopener provides express middleware that sets the Cross-Origin-Opener-Policy (COOP) response header on every response.
crossoriginresource
Package crossoriginresource provides express middleware that sets the Cross-Origin-Resource-Policy (CORP) response header on every response.
Package crossoriginresource provides express middleware that sets the Cross-Origin-Resource-Policy (CORP) response header on every response.
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 fresh, cryptographically random nonce for every request and emits a Content-Security-Policy header whose script-src directive includes that nonce, enabling specific inline scripts to be allow-listed safely.
Package cspnonce provides middleware that generates a fresh, cryptographically random nonce for every request and emits a Content-Security-Policy header whose script-src directive includes that nonce, enabling specific 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 whether browsers speculatively resolve the DNS names of links and resources on a page.
Package dnsprefetch provides middleware that sets the X-DNS-Prefetch-Control response header, controlling whether browsers speculatively resolve the DNS names of links and resources on a page.
downloadheader
Package downloadheader provides express middleware that marks responses as file downloads by setting the Content-Disposition response header to "attachment".
Package downloadheader provides express middleware that marks responses as file downloads by setting the Content-Disposition response header to "attachment".
errorjson
Package errorjson provides an express error-handling middleware that renders unhandled errors as a JSON object of the form {"error": "<message>"}.
Package errorjson provides an express error-handling middleware 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 express 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 express 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 express middleware that answers requests for /favicon.ico, short-circuiting them before they reach application routes or logging.
Package favicon provides express 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 fixed set of boolean feature flags to every request, letting downstream handlers gate behavior on named features.
Package featureflag provides middleware that attaches a fixed set of boolean feature flags to every request, letting downstream 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>, <iframe>, <embed>, or <object>, 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>, <iframe>, <embed>, or <object>, 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 conforming browsers to access the site only over HTTPS.
Package hsts provides middleware that sets the HTTP Strict-Transport-Security (HSTS) response header, instructing conforming browsers to access the site only over HTTPS.
ienoopen
Package ienoopen provides middleware that sets the X-Download-Options response header to the single value "noopen".
Package ienoopen provides middleware that sets the X-Download-Options response header to the single value "noopen".
ipallowlist
Package ipallowlist provides middleware that only permits requests whose client IP address matches a configured allowlist of exact addresses or CIDR ranges, rejecting everything else with 403 Forbidden.
Package ipallowlist provides middleware that only permits requests whose client IP address matches a configured allowlist of exact addresses or CIDR ranges, rejecting everything else with 403 Forbidden.
ipblocklist
Package ipblocklist provides middleware that rejects requests whose client IP address matches a configured blocklist of exact addresses or CIDR ranges, responding with 403 Forbidden, and lets every other request through.
Package ipblocklist provides middleware that rejects requests whose client IP address matches a configured blocklist of exact addresses or CIDR ranges, responding with 403 Forbidden, and lets every other request through.
jsonp
Package jsonp provides Express middleware that wraps JSON responses in a JavaScript callback invocation when the request carries a callback query parameter, enabling classic 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 classic cross-origin JSONP requests.
jwtauth
Package jwtauth provides Express middleware that verifies HS256-signed JSON Web Tokens supplied via the Authorization header, gating access to protected routes.
Package jwtauth provides Express middleware that verifies HS256-signed JSON Web Tokens supplied via the Authorization header, gating access to protected routes.
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 Method Not Allowed otherwise.
Package methodallow provides middleware that restricts requests to a configured set of HTTP methods, responding with 405 Method Not Allowed 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 the response header X-Content-Type-Options: nosniff on every request.
Package nosniff provides middleware that sets the response header X-Content-Type-Options: nosniff on every request.
notfound
Package notfound provides a terminal handler that responds with 404 Not Found for requests that fall through the router unmatched.
Package notfound provides a terminal handler that responds with 404 Not Found for requests that fall through the router unmatched.
originagentcluster
Package originagentcluster provides middleware that sets the Origin-Agent-Cluster response header on every response, requesting that the browser place the origin into its own, origin-keyed agent cluster.
Package originagentcluster provides middleware that sets the Origin-Agent-Cluster response header on every response, requesting that the browser place the origin into its own, origin-keyed agent cluster.
origincheck
Package origincheck provides middleware that rejects requests whose Origin header is not in a configured allowlist, mitigating cross-site request forgery (CSRF) and other cross-origin abuse from untrusted callers.
Package origincheck provides middleware that rejects requests whose Origin header is not in a configured allowlist, mitigating cross-site request forgery (CSRF) and other cross-origin abuse from untrusted callers.
pagination
Package pagination provides middleware that parses the common "page" and "limit" query-string parameters into a normalized, bounds-checked Pagination value stored on the request.
Package pagination provides middleware that parses the 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 raised by downstream handlers, logs them, and responds with a generic 500 JSON error so that a single failing request cannot crash the process.
Package panicjson provides middleware that recovers from panics raised by downstream handlers, logs them, and responds with a generic 500 JSON error so that a single failing request cannot crash the process.
permittedcrossdomain
Package permittedcrossdomain provides middleware that sets the X-Permitted-Cross-Domain-Policies response header on every response, controlling whether Adobe clients honor cross-domain policy files served by the site.
Package permittedcrossdomain provides middleware that sets the X-Permitted-Cross-Domain-Policies response header on every response, controlling whether Adobe clients honor cross-domain policy files served by the site.
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 the resolved value.
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 the resolved value.
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 such as analytics and anti-CSRF checks.
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 such as analytics and anti-CSRF checks.
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 the browser attaches to outgoing requests originated from your pages.
Package referrerpolicy provides middleware that sets the Referrer-Policy response header, controlling how much referrer information the browser attaches to outgoing requests originated from your pages.
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 maintains a per-process sequential counter of the total number of requests handled.
Package requestcounter provides middleware that maintains a per-process sequential counter of the total number of requests handled.
requestdump
Package requestdump provides development middleware that records a snapshot of each incoming request (method, path, headers, and capture time) into a bounded, thread-safe ring buffer for later inspection.
Package requestdump provides development middleware that records a snapshot of each incoming request (method, path, headers, and capture time) into a bounded, thread-safe ring buffer for later inspection.
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 principal has already been placed on the request by an earlier middleware.
Package requireauth provides middleware that rejects requests unless an authenticated principal has already been placed on the request by an 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 by default).
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 by default).
rewrite
Package rewrite provides URL-rewriting middleware.
Package rewrite provides URL-rewriting middleware.
rolecheck
Package rolecheck provides middleware that authorizes a request only when the caller holds at least one of a configured set of roles.
Package rolecheck provides middleware that authorizes a request only when the caller holds at least one of a configured set of roles.
sanitize
Package sanitize provides middleware that strips HTML tags from every query-string value on the incoming request, mitigating trivial reflected cross-site-scripting (XSS) vectors that flow through query parameters.
Package sanitize provides middleware that strips HTML tags from every query-string value on the incoming request, mitigating trivial reflected cross-site-scripting (XSS) vectors that flow through query parameters.
scopecheck
Package scopecheck provides middleware that authorizes a request only when the caller holds every one of a configured set of scopes.
Package scopecheck provides middleware that authorizes a request only when the caller holds every one of a configured set of 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' network panel.
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' network panel.
signedcookies
Package signedcookies provides middleware that verifies a tamper-evident, HMAC-signed cookie and exposes its plaintext value to downstream handlers.
Package signedcookies provides middleware that verifies a tamper-evident, HMAC-signed cookie and exposes its plaintext 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 before the client is answered.
Package timeout provides middleware that bounds the time a downstream handler chain may take before the client is answered.
tokenheader
Package tokenheader provides generic middleware that validates an opaque token carried in a single, configurable request header.
Package tokenheader provides generic middleware that validates an opaque token carried in a single, configurable request header.
trailingslash
Package trailingslash provides middleware that enforces a consistent trailing-slash policy on request paths by redirecting requests that do not conform.
Package trailingslash provides middleware that enforces a consistent trailing-slash policy on request paths by redirecting requests that do not conform.
uptime
Package uptime provides middleware that reports how long the middleware -- and, by extension, the process serving requests -- has been running.
Package uptime provides middleware that reports how long the middleware -- and, by extension, the process serving requests -- 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.
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.
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 express middleware that sets the legacy X-XSS-Protection response header on every response.
Package xssfilter provides express middleware that sets the legacy X-XSS-Protection response header on every response.
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 nanoid generates compact, URL-safe, cryptographically random identifiers, a Go port of the npm "nanoid" package.
Package nanoid generates compact, URL-safe, cryptographically random identifiers, a Go port of the npm "nanoid" package.
Package negotiator is an HTTP content negotiation helper, a stdlib-only Go port of the npm "negotiator" package (https://www.npmjs.com/package/negotiator).
Package negotiator is an HTTP content negotiation helper, a stdlib-only Go port of the npm "negotiator" package (https://www.npmjs.com/package/negotiator).
Package nodepath is a standard-library-only Go port of Node.js's POSIX "path" module (https://nodejs.org/api/path.html), the utility Express and virtually every Node program uses to manipulate filesystem path strings.
Package nodepath is a standard-library-only Go port of Node.js's POSIX "path" module (https://nodejs.org/api/path.html), the utility Express and virtually every Node program uses to manipulate filesystem path strings.
Package numberformat is a standard-library-only Go port of the number presentation helpers popularised by the npm packages numeral.js and accounting.js, which Express/Node apps use to render numbers for humans: thousands grouping, fixed-decimal formatting, currency and percentage formatting, ordinal suffixes and compact "1.2k / 3.4M" abbreviation.
Package numberformat is a standard-library-only Go port of the number presentation helpers popularised by the npm packages numeral.js and accounting.js, which Express/Node apps use to render numbers for humans: thousands grouping, fixed-decimal formatting, currency and percentage formatting, ordinal suffixes and compact "1.2k / 3.4M" abbreviation.
Package onfinished registers callbacks that run when an HTTP response finishes, mirroring the behavior of the npm on-finished library (https://www.npmjs.com/package/on-finished) using only the Go standard library.
Package onfinished registers callbacks that run when an HTTP response finishes, mirroring the behavior of the npm on-finished library (https://www.npmjs.com/package/on-finished) using only the Go standard library.
Package otpauth builds and parses otpauth:// key URIs, a stdlib-only Go port of the URI portion of the npm "otpauth" library (https://www.npmjs.com/package/otpauth).
Package otpauth builds and parses otpauth:// key URIs, a stdlib-only Go port of the URI portion of the npm "otpauth" library (https://www.npmjs.com/package/otpauth).
Package parseurl parses the URL of an incoming HTTP request into its components, a stdlib-only Go port of the npm package "parseurl" (https://www.npmjs.com/package/parseurl).
Package parseurl parses the URL of an incoming HTTP request into its components, a stdlib-only Go port of the npm package "parseurl" (https://www.npmjs.com/package/parseurl).
Package pbkdf2hash implements PBKDF2-HMAC-SHA256 key derivation together with a self-describing, textual password-hash encoding.
Package pbkdf2hash implements PBKDF2-HMAC-SHA256 key derivation together with a self-describing, textual 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 how many execute concurrently at any instant.
Package plimit provides a faithful port of the npm p-limit library: it runs an unbounded number of scheduled functions while capping how many execute concurrently at any instant.
Package pluralize pluralizes and singularizes English words.
Package pluralize pluralizes and singularizes English words.
Package prettybytes converts a number of bytes into a compact, human readable string such as "1.34 kB" or "1.5 MiB".
Package prettybytes converts a number of bytes into a compact, human readable string such as "1.34 kB" or "1.5 MiB".
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 used by Express for req.range and by static file servers to implement partial-content (HTTP 206) responses.
Package rangeparser parses the HTTP Range header, a port of the npm "range-parser" package used by Express for req.range and by static file servers to implement partial-content (HTTP 206) responses.
Package retry retries a function with exponential backoff.
Package retry 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 semver is a standard-library-only Go port of the npm "semver" package (https://www.npmjs.com/package/semver), the reference implementation of Semantic Versioning 2.0.0 (https://semver.org) used throughout the Node and Express ecosystems.
Package semver is a standard-library-only Go port of the npm "semver" package (https://www.npmjs.com/package/semver), the reference implementation of Semantic Versioning 2.0.0 (https://semver.org) used throughout the Node and Express ecosystems.
Package sha256hex provides small, allocation-light helpers that hash bytes or strings and return the digest as a lowercase hexadecimal string.
Package sha256hex provides small, allocation-light helpers that hash bytes or strings and return the digest as a lowercase hexadecimal string.
Package shortid is a standard-library-only short, URL-friendly unique id generator inspired by the npm "shortid" library.
Package shortid is a standard-library-only 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.
Package slugify converts strings into URL-safe slugs, mirroring the behavior of the npm "slugify" library.
Package snowflake is a standard-library-only implementation of the Twitter Snowflake distributed ID scheme, echoing the design of popular npm libraries such as "snowflake-id" and the Go package bwmarrin/snowflake.
Package snowflake is a standard-library-only implementation of the Twitter Snowflake distributed ID scheme, echoing the design of popular npm libraries such as "snowflake-id" and the Go package bwmarrin/snowflake.
Package sqlstring provides MySQL-style value and identifier escaping and query formatting.
Package sqlstring provides MySQL-style value and identifier escaping and query formatting.
Package stats is a standard-library-only Go port of the core of the npm package simple-statistics (https://simplestatistics.org), providing the descriptive-statistics helpers that data-facing Express/Node services reach for: measures of central tendency (Mean, Median, Mode and the geometric and harmonic means), dispersion (Variance, StandardDeviation and their sample variants, Range, InterquartileRange, MedianAbsoluteDeviation), quantiles (Quantile, Percentile), bivariate measures (Covariance, Correlation, LinearRegression) and a few combinatorial functions (Factorial, Combinations, Permutations).
Package stats is a standard-library-only Go port of the core of the npm package simple-statistics (https://simplestatistics.org), providing the descriptive-statistics helpers that data-facing Express/Node services reach for: measures of central tendency (Mean, Median, Mode and the geometric and harmonic means), dispersion (Variance, StandardDeviation and their sample variants, Range, InterquartileRange, MedianAbsoluteDeviation), quantiles (Quantile, Percentile), bivariate measures (Covariance, Correlation, LinearRegression) and a few combinatorial functions (Factorial, Combinations, Permutations).
Package statuses maps between HTTP status codes and their standard reason phrases and classifies codes by behavior.
Package statuses maps between HTTP status codes and their standard reason phrases and classifies codes by behavior.
Package stringdistance is a standard-library-only Go collection of the string similarity and edit-distance algorithms distributed on npm as leven, fast-levenshtein, string-similarity, natural and talisman, which Express/Node apps use for fuzzy matching, spell correction and deduplication.
Package stringdistance is a standard-library-only Go collection of the string similarity and edit-distance algorithms distributed on npm as leven, fast-levenshtein, string-similarity, natural and talisman, which Express/Node apps use for fuzzy matching, spell correction and deduplication.
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 rate-limits how often a function may run, invoking it at most once per a fixed wait duration.
Package throttle rate-limits how often a function may run, invoking it at most once per a fixed wait duration.
Package timingsafe compares byte slices and strings in constant time to avoid leaking secrets through timing side channels.
Package timingsafe compares byte slices and strings in constant time to avoid leaking secrets through timing side channels.
Package titlecase converts strings to Title Case, capitalizing the first letter of each word.
Package titlecase converts strings to Title Case, capitalizing the first letter of each word.
Package totp implements time-based one-time passwords as defined in RFC 6238, the short numeric codes that authenticator apps such as Google Authenticator, Authy, and 1Password display for two-factor authentication.
Package totp implements time-based one-time passwords as defined in RFC 6238, the short numeric codes that authenticator apps such as Google Authenticator, Authy, and 1Password display for two-factor authentication.
Package truncate shortens a string to a maximum length, appending an ellipsis when content is cut.
Package truncate shortens a string to a maximum length, appending an ellipsis when content is cut.
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.
Package uidsafe generates cryptographically secure, URL-safe unique identifiers.
Package ulid generates and decodes Universally Unique Lexicographically Sortable Identifiers (ULIDs).
Package ulid generates and decodes Universally Unique Lexicographically Sortable Identifiers (ULIDs).
Package uniq removes duplicate elements from a slice, preserving order.
Package uniq removes duplicate elements from a slice, preserving order.
Package urljoin joins URL path segments together, normalizing slashes.
Package urljoin joins URL path segments together, normalizing slashes.
Package uuid generates and parses RFC 4122 universally unique identifiers.
Package uuid generates and parses RFC 4122 universally unique identifiers.
Package validator provides lightweight, fluent input validation for express handlers, in the spirit of the npm "express-validator" package.
Package validator provides lightweight, fluent input validation for express handlers, in the spirit of the npm "express-validator" package.
Package validatorjs is a standalone port of the popular npm "validatorjs" (and the closely related "validator.js") string validation library to idiomatic Go.
Package validatorjs is a standalone port of the popular npm "validatorjs" (and the closely related "validator.js") string validation library to idiomatic Go.
Package vary manipulates the HTTP Vary response header.
Package vary manipulates the HTTP Vary response header.
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.
Package xid generates globally unique, sortable 12-byte identifiers encoded as 20-character base32 strings.
Package xid generates globally unique, sortable 12-byte identifiers encoded as 20-character base32 strings.

Jump to

Keyboard shortcuts

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