Server API

    Server Lifecycle and Request Handlers

    HTTP.ServerType
    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.

    source
    HTTP.StreamType
    Stream

    Bidirectional 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.

    source
    HTTP.listen!Function
    listen!(server) -> Server

    Start a configured Server asynchronously and return it.

    source
    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...) -> Server

    Start 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.

    source
    HTTP.listenFunction
    listen(handler, args...; kwargs...)

    Run listen! in the foreground, blocking until the server is closed.

    source
    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...) -> Server

    Start 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.

    source
    HTTP.serveFunction
    serve(handler, args...; kwargs...)

    Run serve! in the foreground, blocking until the server is closed.

    source
    HTTP.streamhandlerFunction
    streamhandler(request_handler) -> stream handler

    Adapter that takes a request handler and returns a stream handler.

    source
    HTTP.servefileFunction
    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.

    source
    HTTP.fileserverFunction
    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.

    source
    HTTP.servecontentFunction
    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.

    source
    HTTP.forcecloseFunction
    forceclose(server)

    Immediately stop accepting new connections and close all tracked connections.

    source
    HTTP.portFunction
    port(server) -> Int

    Return the bound port for server, or the configured port if it has not started listening yet.

    source
    HTTP.startreadFunction
    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, ...).

    source
    HTTP.startwriteFunction
    startwrite(stream) -> Response

    Start 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.

    source
    HTTP.setstatusFunction
    setstatus(stream, status) -> nothing

    Set the response status for a server-side Stream before response writing starts.

    source
    HTTP.addtrailerFunction
    addtrailer(stream, header_or_headers) -> nothing

    Append response trailers for a server-side Stream. Trailers are emitted when the response body is closed, so call this before closewrite(stream).

    source
    HTTP.closereadFunction
    closeread(stream) -> Response

    Close 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.

    source

    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.HandlerType
    Handler

    Abstract 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.

    source
    HTTP.Handlers.MiddlewareType
    Middleware

    Abstract 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.

    source
    HTTP.Handlers.RouterType
    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.

    source
    HTTP.Handlers.NodeType
    Node

    Internal trie node used by Router to store exact, wildcard, and parameterized path segments.

    source
    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) -> Nothing

    Register 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"))
    end
    source
    HTTP.Handlers.getrouteFunction
    HTTP.getroute(req) -> Union{Nothing, String}

    Retrieve the original route registration string for a request after its target has been matched against a router.

    source
    HTTP.Handlers.getparamsFunction
    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.

    source
    HTTP.Handlers.getparamFunction
    HTTP.getparam(req, name, default=nothing) -> Any

    Retrieve a matched path parameter with name name from request context.

    source
    HTTP.Handlers.handlertimeoutFunction
    handlertimeout(timeout_s; status=503, body="handler timed out", content_type="text/plain; charset=utf-8")
        -> middleware

    Wrap 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.

    source

    Server-Sent Events

    HTTP.SSEEventType
    SSEEvent(data; event=nothing, id=nothing, retry=nothing)

    Server-Sent Event value used for both client-side parsing and server-side emission.

    Fields:

    • data: concatenated data: lines joined by `

    `

    • event: optional event name
    • id: last event id in effect when the event dispatched
    • retry: last valid retry hint in milliseconds
    • fields: all observed fields collected into a string dictionary
    source
    HTTP.SSEStreamType
    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.

    source
    HTTP.sse_streamFunction
    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) -> SSEStream

    Create 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.

    source