LEVIATHAN v962456e · 962456eee1

Standard Library

class HttpResponseReader

Collects a client's incoming bytes and turns them into an HttpResponse.

since 0.1.0-alpha.1linuxwindowswasm

Overview

HttpClient uses it: the text received from the server is gathered with feed, and when the server closes the connection finish parses it and passes the response to your callback. You only need it to read a response from a stream you opened yourself.

Examples

HttpResponseReader reader = HttpResponseReader(TcpStream(-1), (resp) => {
    console.writeln("${resp.status} ${resp.reason()}: ${resp.body}");
});
reader.feed("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhe");
reader.feed("llo");
reader.finish();
200 OK: hello

Constructors

new

new(TcpStream s, (HttpResponse) => void cb)

Creates a reader for a stream and the callback that receives the finished response.

Parameters

s
The stream the response arrives on.
cb
The function called with the parsed response.

Examples

HttpResponseReader reader = HttpResponseReader(TcpStream(-1), (resp) => console.writeln(resp.status));
reader.feed("HTTP/1.1 404 Not Found\r\n\r\n");
reader.finish();
404

Methods

feed

feed(string chunk) -> void

Adds received text to the response being collected.

Parameters

chunk
The next piece of the response, exactly as received.

Examples

HttpResponseReader reader = HttpResponseReader(TcpStream(-1), (resp) => console.writeln(resp.body));
reader.feed("HTTP/1.1 200 OK\r\n\r\n");
reader.feed("in two ");
reader.feed("pieces");
reader.finish();
in two pieces

finish

finish() -> void

Parses everything collected so far and passes the response to the callback.

A Transfer-Encoding: chunked body is decoded. Text that is not a valid response gives a response with status 0.

Examples

HttpResponseReader reader = HttpResponseReader(TcpStream(-1), (resp) => console.writeln(resp.status));
reader.feed("not a response");
reader.finish();
0

See also: parse

start

start() -> void

Starts reading from the stream.

Received text is gathered, and when the stream closes the response is parsed and passed to the callback.

Examples

void readResponse(TcpStream stream) {
    HttpResponseReader reader = HttpResponseReader(stream, (resp) => console.writeln(resp.status));
    reader.start();
}
not run — reads from a network connection

See also

  • HttpClient — A simple HTTP client that sends one request per connection and delivers the response to a callback.
  • parse — Fills in the response from a complete response text.