LEVIATHAN v962456e · 962456eee1

Standard Library

class HttpConnection

One client connection served by an HttpServer.

since 0.1.0-alpha.1linux

Overview

The server creates a connection for every client that connects and calls start. The connection reads a request, runs your handler, and sends the response. If your handler throws, the client receives a 500 Internal Server Error and the connection is closed, and the server keeps running. When neither side asks to close, the connection is kept open for the next request, up to maxRequests requests. Request pipelining is not supported: bytes that arrive while a response is being sent close the connection.

You normally do not create connections yourself; use HttpServer.

Examples

Serving one accepted connection

void serve(TcpStream client) {
    HttpConnection conn = HttpConnection(client, (req) => HttpResponse(200, "hello"));
    conn.start();
}
not run — needs a network connection

Constructors

new

Creates a connection around an accepted client stream.

Nothing is read until start is called.

Parameters

c
The stream connected to the client.
h
The handler that turns each request into a response.

Fields

closed

bool closed

Becomes true once the connection has been closed.

maxRequests

int maxRequests

The most requests answered on one connection before it is closed. The default is 100.

served

int served

The number of requests answered so far on this connection.

Methods

closeConn

closeConn() -> void

Closes the connection.

It is safe to call more than once. A streaming response that is still open is abandoned.

start

start() -> void

Begins reading requests from the client.

Each complete request is passed to the handler, and its response is sent back. The connection closes itself when the client disconnects or asks for it.

See also

  • HttpServer — A web server that listens on a port and answers each request with a handler function.