Server API
Server Lifecycle and Request Handlers
HTTP.Server — Type
Server(; network="tcp", address="127.0.0.1:0", handler, stream=false, ...)Stateful HTTP server handle returned by listen! and serve!.
The handle owns the listener, background task, active-connection set, and timeout configuration. Keep it around for lifecycle operations such as port, wait(server), close(server), or forceclose.
Timeout fields are stored in nanoseconds. Use the convenience listen! and serve! keywords to configure request-read, header-read, response-write, and idle deadlines without constructing a Server manually.
HTTP.Stream — Type
StreamBidirectional HTTP stream used by listen!, serve!, HTTP.open, and stream-oriented request/response handlers.
Server-side streams expose request metadata through startread(stream) and let handlers consume request bytes from the stream directly before writing a response. Client-side streams let callers write a request body first, then switch to reading the response head/body from the same object.
HTTP.listen! — Function
listen!(server) -> ServerStart a configured Server asynchronously and return it.
listen!(handler, host="127.0.0.1", port=8080;
read_timeout_ns=0, read_header_timeout_ns=0, write_timeout_ns=0,
idle_timeout_ns=0, max_header_bytes=1*1024*1024,
listenany=false, reuseaddr=true, backlog=128) -> Server
listen!(handler, port; kwargs...) -> Server
listen!(handler, listener; kwargs...) -> ServerStart a streaming HTTP server and return the running Server.
handler is called with an HTTP.Stream and is responsible for reading the request and writing the response. Timeout keywords ending in _ns are nanoseconds; read_timeout, read_header_timeout, write_timeout, and idle_timeout accept seconds. The older readtimeout keyword is accepted as a seconds-valued migration alias for read_timeout.
HTTP.listen — Function
listen(handler, args...; kwargs...)Run listen! in the foreground, blocking until the server is closed.
HTTP.serve! — Function
serve!(handler, host="127.0.0.1", port=8080;
read_timeout_ns=0, read_header_timeout_ns=0,
write_timeout_ns=0, idle_timeout_ns=0,
max_header_bytes=1*1024*1024, listenany=false, reuseaddr=true,
backlog=128) -> Server
serve!(handler, port; kwargs...) -> Server
serve!(handler, listener; kwargs...) -> ServerStart an HTTP server and return the running Server.
handler is called with an HTTP.Request and must return an HTTP.Response. Use listen! for the lower-level HTTP.Stream handler path. Timeout keywords ending in _ns are nanoseconds; the older readtimeout keyword is accepted as a seconds-valued migration alias for read_timeout.
HTTP.serve — Function
serve(handler, args...; kwargs...)Run serve! in the foreground, blocking until the server is closed.
HTTP.streamhandler — Function
streamhandler(request_handler) -> stream handlerAdapter that takes a request handler and returns a stream handler.
HTTP.servefile — Function
servefile(request, path; ...)Serve the file or directory at path for request using servecontent semantics and canonical redirect handling.
Only GET and HEAD are served. Directory requests resolve index_file; missing files return 404, and unsafe or invalid request paths return 400.
HTTP.fileserver — Function
fileserver(root; ...)Return a request handler that serves static files rooted at root.
If spa_fallback is provided, missing request paths whose final segment does not look like a filename are served from that file within root. Missing asset-like paths still return 404.
The returned function is a normal Request -> Response handler suitable for serve!, routers, and middleware.
HTTP.servecontent — Function
servecontent(request, source; ...)Build a response for request from byte-backed or seekable content while handling conditional headers and single-byte-range requests.
source may be an AbstractVector{UInt8} or a seekable IO. The helper sets Content-Type, Content-Length, Last-Modified, ETag, Accept-Ranges, and Content-Range when enough information is provided. It returns 304, 412, or 416 responses for the corresponding precondition/range outcomes.
HTTP.forceclose — Function
forceclose(server)Immediately stop accepting new connections and close all tracked connections.
HTTP.startread — Function
startread(stream)Begin the readable side of stream.
For client streams, this finalizes request writes if needed, executes the HTTP exchange, and returns the response metadata without buffering the response body. Subsequent reads on stream consume the response body.
For server streams, this returns request metadata only. The request body stays attached to stream itself, so handlers should read it with read(stream) or readbytes!(stream, ...).
HTTP.startwrite — Function
startwrite(stream) -> ResponseStart the response side of a server-side Stream and return the response metadata. Calling write(stream, data) starts writing automatically; use startwrite explicitly when you need headers to be sent before body bytes.
HTTP.setstatus — Function
setstatus(stream, status) -> nothingSet the response status for a server-side Stream before response writing starts.
HTTP.addtrailer — Function
addtrailer(stream, header_or_headers) -> nothingAppend response trailers for a server-side Stream. Trailers are emitted when the response body is closed, so call this before closewrite(stream).
HTTP.closeread — Function
closeread(stream) -> ResponseClose the readable side of stream and return its response metadata.
If the response body has already been fully consumed, this is effectively a no-op. If unread response bytes remain, the underlying client connection is not reused.
Routing and Middleware
The router and middleware helpers live in HTTP.Handlers and are also available through HTTP.Router, HTTP.register!, and the related imported aliases for compatibility.
HTTP.Handlers.Handler — Type
HandlerAbstract type for the handler interface that exists for documentation purposes. A Handler is any function of the form f(req::HTTP.Request) -> HTTP.Response. There is no requirement to subtype Handler and users should not rely on or dispatch on Handler.
For advanced cases, a Handler function can also be of the form f(stream::HTTP.Stream) -> Nothing. In this case, the server would be run like HTTP.listen(f, ...). Any middleware used with a stream handler also needs to accept and return a stream handler.
HTTP.Handlers.Middleware — Type
MiddlewareAbstract type for the middleware interface that exists for documentation purposes. A Middleware is any function of the form f(::Handler) -> Handler. There is no requirement to subtype Middleware and users should not rely on or dispatch on Middleware.
HTTP.Handlers.Router — Type
HTTP.Handlers.Router([_404], [_405], [middleware])
HTTP.Router([_404], [_405], [middleware])Define a router object that maps incoming requests by path to registered routes and associated handlers.
Routes are matched by method and path segments. Supported segment patterns are:
- exact segments, such as
/users - named variables, such as
/users/{id} - named variables with regular expressions, such as
/files/{name:\w+} - single-segment wildcards with
* - trailing multi-segment wildcards with
**
Matched route metadata is stored on the request context and can be read with getroute, getparams, and getparam.
HTTP.Handlers.Node — Type
NodeInternal trie node used by Router to store exact, wildcard, and parameterized path segments.
HTTP.Handlers.register! — Function
register!(router, method, path, handler) -> Nothing
register!(router, path, handler) -> Nothing
register!(handler, router, method, path) -> Nothing
register!(handler, router, path) -> NothingRegister a new route in router.
The path may include named path variables like /{id} or wildcard segments. The 3-argument form registers the handler for all methods.
handler may be a Request -> Response handler for serve! or a Stream -> Nothing handler for listen!, as long as the router is used with the matching server entrypoint.
The handler-first forms accept the handler as the first positional argument so that do-block syntax may be used:
register!(router, "GET", "/users/{id}") do req
return HTTP.Response(200; body = HTTP.Handlers.getparam(req, "id"))
endHTTP.Handlers.getroute — Function
HTTP.getroute(req) -> Union{Nothing, String}Retrieve the original route registration string for a request after its target has been matched against a router.
HTTP.Handlers.getparams — Function
HTTP.getparams(req) -> Union{Nothing, Dict{String, String}}Retrieve any matched path parameters from the request context.
Returns nothing when the request has not been routed or the route contained no path variables.
HTTP.Handlers.getparam — Function
HTTP.getparam(req, name, default=nothing) -> AnyRetrieve a matched path parameter with name name from request context.
HTTP.Handlers.getcookies — Function
HTTP.getcookies(req) -> Vector{Cookie}Retrieve any parsed cookies from a request context.
HTTP.Handlers.handlertimeout — Function
handlertimeout(timeout_s; status=503, body="handler timed out", content_type="text/plain; charset=utf-8")
-> middlewareWrap a request handler with a wall-clock timeout and synthesize a timeout response when the handler does not finish in time.
The wrapped handler receives a child RequestContext whose deadline is bounded by both the configured timeout and any existing parent request deadline. On timeout, the child context is canceled and a response with status, body, and content_type is returned.
Server-Sent Events
HTTP.SSEEvent — Type
SSEEvent(data; event=nothing, id=nothing, retry=nothing)Server-Sent Event value used for both client-side parsing and server-side emission.
Fields:
data: concatenateddata:lines joined by `
`
event: optional event nameid: last event id in effect when the event dispatchedretry: last valid retry hint in millisecondsfields: all observed fields collected into a string dictionary
HTTP.SSEStream — Type
SSEStream(; max_len=16*1024*1024)Writable Server-Sent Events body used by sse_stream(status).
SSEStream is also an AbstractBody, so server response writers can stream it directly to HTTP/1 or HTTP/2 connections while user code keeps pushing SSEEvent values into it.
HTTP.sse_stream — Function
sse_stream(status=200; max_len=16*1024*1024, ...) -> Response
sse_stream(status, f; max_len=16*1024*1024, ...) -> Response
sse_stream(response; max_len=16*1024*1024) -> SSEStream
sse_stream(response, f; max_len=16*1024*1024) -> SSEStreamCreate or configure a server-sent events response.
sse_stream(status; ...) constructs a Response with an SSEStream body, sets the standard SSE headers, and returns the response for manual event emission.
sse_stream(status) do stream ... end is the usual server helper. It creates the response, runs the producer on a background task, and closes the stream automatically when the callback finishes.
The response-accepting forms are for responses that already have an SSEStream body.