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();
}
Constructors
new
new(TcpStream c, (HttpRequest) => HttpResponse h)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 closedBecomes true once the connection has been closed.
maxRequests
int maxRequestsThe most requests answered on one connection before it is closed. The default is 100.
served
int servedThe number of requests answered so far on this connection.
Methods
closeConn
closeConn() -> voidCloses the connection.
It is safe to call more than once. A streaming response that is still open is abandoned.
start
start() -> voidBegins 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.