HTTP support for moonbitlang/core/async.

    #Making simple HTTP request

    Simple HTTP request can be made in just one line:

    ///|
    #cfg(any(target="native", target="js"))
    async test {
    let (response, body) = @http.get("https://www.moonbitlang.com")
    inspect(response.code, content="200")
    assert_true(body.text().has_prefix("<!doctype html>"))
    }

    Here body represent collected response body of the request. Use .binary() to get its raw binary content, .text() to decode it as UTF-8 encoded text, or .json() to decode it as UTF-8 encoded JSON.

    #Streaming message body

    For HTTP messages with large body, collecting the whole body in memory could be a bad idea. The @http package also provide convenient API for manipulating message body streamingly:

    ///|
    #cfg(any(target="native", target="js"))
    async test {
    let (response, conn) = @http.get_stream("https://www.moonbitlang.com")
    defer conn.close()
    inspect(response.code, content="200")
    let body = conn.text.read_all()
    assert_true(body.has_prefix("<!doctype html>"))
    }

    Here, @http.get_stream(url) performs a GET request to URL, and returns the response header from the server, plus the HTTP connection assigned for this request. The content of response body can be read from the connection through the @io.BinaryReader interface, or through the @io.TextReader interface using the .text view on the connection. The connection must be closed via .close() after finishing the request.

    @http.put_stream and @http.post_stream work similarly, except that the response header will not be returned immediately. @http.put_stream and @http.post_stream only returns the HTTP connection for the request. The caller should first write the content of request body through the @io.BinaryWriter interface on the connection (or through the @io.TextWriter interface via .text). After finishing the request body, .end_request should be invoked on the connection to finish the request and obtain response header from the server. After .end_request, body of response message can be read from the connection as in the @http.get_stream case above.

    #Generic HTTP client

    When performing multiple requests to the same host, sharing and reusing HTTP connection can save a lot of resource. The generic @http.Client type provides connection pool backed HTTP client support. A HTTP client can be created via @http.Client(..) and must be closed via .close(). Users can perform requests through the client via .request(..), .get(..) etc., the semantic of these methods are similar to @http.request(..), @http.get(..) etc., except that they can reuse the client's existing connections to save resource. Multiple requests can be performed on the same client concurrently, the client will automatically create new connection if necessary to fulfill requests.

    note: currently the @http.Client is just a placeholder that create a new connection for every request. Proper connection pool support will be implemented in the near future.

    #JavaScript compatibility

    All HTTP client API, including the toplevel @http.xxx helpers and the generic @http.Client type, has browser-compatible JavaScript backend support using fetch API, Notice that some feature, such as proxy and streaming request body building, are not supported on JavaScript backend due to limitation of fetch API.

    #Writing HTTP servers

    The recommended way to create HTTP servers is @http.Server::run_forever(..). A HTTP server should first get created via @http.Server(..), after that, server.run_forever(f) automatically start and run the server. The callback function f is used to handle HTTP requests. It receives two parameters:

    • the request to process
    • a @http.ServerConnection that can be used to read request body or send response.

    Content of the incoming request body can be read streamingly using @io.BinaryReader interface (or @io.TextReader interface through the builtin .text view) on the @http.ServerConnection directly.

    The procedure to send a response is:
    1. initiate a response and send response header via .send_response()
    2. send response body by using the @http.ServerConnection as @io.BinaryWriter. Text content can be written directly via conn.text through the @io.TextWriter interface as well
    3. (optional) complete the response via .end_response(). If .end_response() is not called, it will be called automatically after f returns normally.

    Here's an example server that returns 404 to every request:

    ///|
    /// A simple HTTP server that return 404 for every request
    #cfg(target="native")
    pub async fn server(listen_addr : @socket.Addr) -> Unit {
    @http.Server(listen_addr).run_forever((request, conn) => {
    conn.send_response(404, "NotFound")
    conn.text.write("`\{request.path}` not found")
    })
    }

    Headers

    type Headers = Map[CaseInsensitiveString, String]

    Type for HTTP headers. The names of headers are case insensitive.

    The RFC requires that multiple header entries with the same name should be semantically equivalent to concatenating values with comma, so a Map with unique keys can be used to represent headers.

    One important exception to the above rule is the Set-Cookie header, which is handled specially via the Cookie type.

    InvalidMessage

    Error raised when the user intent to send an invalid HTTP message, for example sending with an invalid extension method name, or sending a fixed-length body with incorrect amount of data.

    ProtocolError

    pub suberror ProtocolError {
    BadMessage
    HttpVersionNotSupported(String)
    NotImplemented
    } derive(
    Debug
    ,
    ToJson
    )

    Error raised when parsing a HTTP message

    ProxyError

    Error raised when the proxy responded with a non-2XX response code

    UriParseError

    Error raised when an invalid URI is specified

    CaseInsensitiveString

    pub(all) struct CaseInsensitiveString(String) derive(
    ToJson
    )

    String type with case insensitive comparison (in the ASCII sense). This type is implicitly convertible from String & string literal.

    CaseInsensitiveString::compare

    CaseInsensitiveString::equal

    CaseInsensitiveString::hash

    CaseInsensitiveString::to_string

    fn CaseInsensitiveString::to_string(self : CaseInsensitiveString) -> String

    Client

    type Client

    A generic HTTP client

    Client::Client

    fn Client::Client(headers? : Map[CaseInsensitiveString, String]) -> Client

    Create a new HTTP client.

    headers, if present, set common headers for all requests going through this client. The ownership of headers will be transferred to the new client, so headers should not be used by the caller later. The following headers is automatically set, and must not be specified in headers:

    • Host
    • Content-Length, Accept-Encoding, Transfer-Encoding

    Client::close

    fn Client::close(_ : Client) -> Unit

    Close a HTTP client, release associated resource

    Client::get

    async fn Client::get(self : Client, uri : StringView, extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a HTTP GET request to uri. Return response header and collect whole response body.

    See @http.Client::request for more details.

    Client::get_stream

    async fn Client::get_stream(self : Client, url : StringView, extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, ClientConnection)

    Perform a GET request on url through a HTTP client. Return the response header and the client connection assigned for the request. Content of response body can be read through the @io.BinaryReader interface (or @io.TextReader interface through the builtin .text view) on the connection. The connection must be closed after the connection become unused.

    See @http.Client::request for more details on the optional parameters.

    Client::post_binary

    async fn Client::post_binary(self : Client, uri : StringView, content : BytesView, extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a POST request on url with binary request body through a HTTP client. Return the response header and collected response body.

    See @http.Client::request for more details on the optional parameters.

    Client::post_json

    async fn Client::post_json(self : Client, uri : StringView, content :
    Json
    , extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a POST request on url with UTF-8 encoded JSON request body through a HTTP client. Return the response header and collected response body.

    See @http.Client::request for more details on the optional parameters.

    Client::post_stream

    async fn Client::post_stream(self : Client, url : StringView, extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> ClientConnection

    Perform a POST request on url through a HTTP client. Return the client connection assigned for this request. Request body can be written through the @io.BinaryWriter interface on the connection, or through the @io.TextWriter interface using the builtin .text view on the connection. When the request body is completely written, end_request() should be called on the connection to terminate the request and obtain response header from the server. After receiving the response header, Response body can be read through the @io.BinaryReader interface (or @io.TextReader interface through the builtin .text view) on the connection. The connection must be closed after the connection become unused.

    See @http.Client::request for more details on the optional parameters.

    Client::post_text

    async fn Client::post_text(self : Client, uri : StringView, content : StringView, extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a POST request on url with UTF-8 encoded text request body through a HTTP client. Return the response header and collected response body.

    See @http.Client::request for more details on the optional parameters.

    Client::put_binary

    async fn Client::put_binary(self : Client, uri : StringView, content : BytesView, extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a PUT request on url with binary request body through a HTTP client. Return the response header and collected response body.

    See @http.Client::request for more details on the optional parameters.

    Client::put_json

    async fn Client::put_json(self : Client, uri : StringView, content :
    Json
    , extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a PUT request on url with UTF-8 encoded JSON request body through a HTTP client. Return the response header and collected response body.

    See @http.Client::request for more details on the optional parameters.

    Client::put_stream

    async fn Client::put_stream(self : Client, url : StringView, extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> ClientConnection

    Perform a PUT request on url through a HTTP client. Return the client connection assigned for this request. Request body can be written through the @io.BinaryWriter interface on the connection, or through the @io.TextWriter interface using the builtin .text view on the connection. When the request body is completely written, end_request() should be called on the connection to terminate the request and obtain response header from the server. After receiving the response header, Response body can be read through the @io.BinaryReader interface (or @io.TextReader interface through the builtin .text view) on the connection. The connection must be closed after the connection become unused.

    See @http.Client::request for more details on the optional parameters.

    Client::put_text

    async fn Client::put_text(self : Client, uri : StringView, content : StringView, extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a PUT request on url with UTF-8 encoded text request body through a HTTP client. Return the response header and collected response body.

    See @http.Client::request for more details on the optional parameters.

    Client::request_binary

    async fn Client::request_binary(self : Client, meth : RequestMethod, url : StringView, body : BytesView, extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a generic HTTP request with binary request body. Server response header and collected response body will be returned.

    See @http.Client::request_stream for more details on the optional parameters.

    Client::request_json

    async fn Client::request_json(self : Client, meth : RequestMethod, url : StringView, body :
    Json
    , extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a generic HTTP request with UTF-8 encoded JSON request body. Server response header and collected response body will be returned.

    See @http.Client::request_stream for more details on the optional parameters.

    Client::request_stream

    async fn Client::request_stream(self : Client, meth : RequestMethod, url : StringView, extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> ClientConnection

    Make a request using a HTTP client. meth specifies the request method and url specifies the target URL of request. Currently only http and https protocols are supported.

    The client will find or allocate a new network connection to fulfill the request. If the request is sent successfully, that connection will be returned. Subsequent workflow with the returned connection is as follows:
    1. request message body can be written to the connection through @io.BinaryWriter interface (or @io.TextWriter interface through the builtin .text view on the connection)
    2. after finish writing all request body content, .end_request() should be invoked on the connection to finish the request and obtain the response header
    3. after obtaining the response header, content of response body can be read through the @io.BinaryReader interface (or @io.TextReader interface through the builtin .text view) on the connection
    4. after finishing the whole request, .close() must be called on the connection to return it to the client

    In addition to common headers specified on client creation, extra HTTP headers can be passed via extra_headers. proxy, if present, specifies the proxy to use for this request.

    If Content-Length is present in extra_headers, it should be the total length of the request body. The request body can still be sent incrementally, but if the actual body being sent is shorter and longer than the provided length, an error will be raised.

    Client::request_text

    async fn Client::request_text(self : Client, meth : RequestMethod, url : StringView, body : StringView, extra_headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a generic HTTP request with UTF-8 encoded text request body. Server response header and collected response body will be returned.

    See @http.Client::request_stream for more details on the optional parameters.

    ClientConnection

    pub struct ClientConnection {
    text :
    Utf8TextView

    // private fields
    }

    Simple HTTP client which connect to a remote host via TCP

    ClientConnection::ClientConnection

    #alias(new, deprecated="`new` is deprecated, use `ClientConnection` instead")
    async fn ClientConnection::ClientConnection(uri : StringView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy, trust? :
    TrustedRoot
    ) -> ClientConnection

    Create a new HTTP client by connecting to a remote host. Host should be specified via protocol://host[:port], where protocol is one of http or https. If protocol is https, a TLS connection will be established, and the certificate of the remote peer will be verified.

    If the protocol is https, trust will determine the trusted root for cert validation. See @tls.TrustedRoot for more details.

    headers can be used to specify persistent headers for the client, i.e. all requests made from this client will share these headers. The ownership of headers will be transferred to the new client, so headers should not be used by the caller later. The following headers must not be specified in headers:

    • Host
    • Content-Length, Transfer-Encoding, Accept-Encoding

    User-Agent may be specified to override the library default.

    If proxy is present, the connection is established through that proxy. See @http.Proxy for details.

    ClientConnection::close

    fn ClientConnection::close(self : ClientConnection) -> Unit

    Close a HTTP client and release underlying resource. In particular close the underlying TCP connection. This function is idempotent: it is safe to call .close() multiple times, only the first .close() call takes effect.

    ClientConnection::drop_all

    Drop all remaining content from a binary reader, until EOF is reached.

    ClientConnection::drop_exactly

    async fn ClientConnection::drop_exactly(self : ClientConnection, len : Int) -> Unit raise
    ReaderError

    reader.drop_exactly(len) drops exactly len bytes from the reader. drop_exactly waits until enough bytes are available. If EOF is reached before enough data is dropped, UnexpectedEof will be raised.

    ClientConnection::end_request

    async fn ClientConnection::end_request(self : ClientConnection, on_informational_response? : async (ResponseHeader) -> Unit) -> ResponseHeader

    End the body of the request currently being sent, and obtain response from the server. Should be called immediately after request body is fully sent.

    Only the header of the response will be received and returned, the response body can be read through ClientConnection as an @io.BinaryReader, or through client.text as an @io.TextReader.

    If the body of the last response is still not consumed, it will be discarded.

    1XX response, except for 101 Switching Protocol, will be automatically processed and discarded, and the returned response is always the final response (or 101). on_informational_response, if present, will be invoked for every skipped 1XX informational response.

    ClientConnection::enter_passthrough_mode

    async fn ClientConnection::enter_passthrough_mode(self : ClientConnection) -> Unit

    Let the client enter "pass through" mode, where the client serve as a TCP tunnel (maybe TLS encrypted) directly. This is useful for the special CONNECT HTTP request and HTTP protocol upgrade.

    In passthrough mode, Read/write the client becomes direct read/write on the underlying connection, and only its @io.BinaryReader and @io.BinaryWriter APIs may be used.

    When entering pass through mode, the client must be in a clean state (i.e. not in the middle of sending a request). Unread data from the body of the last response will be discarded.

    ClientConnection::flush_partial_data

    async fn ClientConnection::flush_partial_data(self : ClientConnection) -> Unit

    Flush all partial data and ensure they are delivered immediately. For writer transformers such as gzip writer, the underlying transport will be flushed as well. The flush is only best-effort: underlying implementation may choose to still buffer some data.

    flush_partial_data IS NOT used to ensure stream integrity: stream termination such as @tls.Tls::shutdown() is a protocol-specific operation. The only purpose of flush_partial_data is to ensure timely delivery of partial data. If the user only cares about eventual integrity of data, flush_partial_data is always UNNECESSARY.

    flush_partial_data mainly deal with userland buffering. It does not, for example, synchronize data to disk for a file system writer.

    ClientConnection::peek

    reader.peek() fetches and returns a chunk of data from the reader. The returned data will not get consumed from the reader: other reader API can still fetch them later.

    The chunk returned by reader.peek() is a copy-free slice of the reader's internal buffer, and its content will be overwritten by subsequent reader operations. So caller of peek MUST NOT use the returned slice after any other BinaryReader operation is invoked on the same reader. If the data need to be kept persistent, copy it via .to_owned().

    The returned chunk will contain at least one byte. If EOF is reached before any data is fetched, None will be returned.

    reader.peek() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.peek() is cancelled, no data will be lost.

    ClientConnection::peek_at_least

    async fn ClientConnection::peek_at_least(self : ClientConnection, min_len : Int) -> BytesView raise
    ReaderError

    reader.peek_at_least(min_len) fetches and returns a chunk containing at least min_len bytes without consuming it. The returned chunk may be larger than min_len.

    The returned view is valid only until another operation is invoked on the same reader. Use .to_owned() to keep the data persistently.

    If EOF is reached before enough data is fetched, UnexpectedEof will be raised. Any shorter trailing data remains buffered and can be fetched by a later reader operation.

    reader.peek_at_least() is cancellation safe as long as the underlying reader implementation is cancellation safe. When it is cancelled, no data will be lost.

    ClientConnection::peek_exactly

    async fn ClientConnection::peek_exactly(self : ClientConnection, len : Int) -> BytesView raise
    ReaderError

    reader.peek_exactly(len) fetches exactly len bytes from the reader. It will wait until enough number of bytes is available. The returned data will not get consumed from the reader: other reader API can still fetch them later.

    The chunk returned by reader.peek_exactly() is a copy-free slice of the reader's internal buffer, and its content will be overwritten by subsequent reader operations. So caller of peek MUST NOT use the returned slice after any other BinaryReader operation is invoked on the same reader. If the data need to be kept persistent, copy it via .to_owned().

    If EOF is reached before enough data is read, UnexpectedEof will be raised. In this case remaining data remain buffered, and can be fetched by other reader operations later.

    reader.peek_exactly() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.peek_exactly() is cancelled, no data will be lost.

    ClientConnection::peek_until

    async fn ClientConnection::peek_until(self : ClientConnection, pattern : BytesView, include_delimiter? : Bool) -> BytesView? raise
    ReaderError

    reader.peek_until(pat, include_delimiter? : Bool = false) fetches content from reader until the byte string pat is found in the reader stream. The returned data will not get consumed from the reader: other reader API can still fetch them later.

    The chunk returned by reader.peek_until() is a copy-free slice of the reader's internal buffer, and its content will be overwritten by subsequent reader operations. So caller of peek MUST NOT use the returned slice after any other BinaryReader operation is invoked on the same reader. If the data need to be kept persistent, copy it via .to_owned().

    If pat is found in the input stream, content before that occurrence is returned. If include_delimiter is true, pat itself is included at the end of the result. The returned data may be empty in this case if include_delimiter is false.

    EOF is implicitly treated as a delimiter by reader.peek_until(). If pat is not found in the input stream when EOF is reached, trailing data before EOF will be returned (or None if there is no trailing data). In this case, the returned data contains no trailing delimiter even if include_delimiter=true. This can be used to detect the presence of trailing delimiter in the input stream.

    reader.peek_until() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.peek_until() is cancelled, no data will be lost.

    ClientConnection::read

    reader.read() fetches and returns a chunk of data from the reader. It will return as fast as possible when new data become available.

    The returned chunk will contain at least one byte. If EOF is reached before any data is fetched, None will be returned.

    reader.read() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.read() is cancelled, no data will be lost.

    ClientConnection::read_all

    Read all remaining content from a binary reader, until EOF is reached.

    ClientConnection::read_at_least

    async fn ClientConnection::read_at_least(self : ClientConnection, min_len : Int) -> Bytes raise
    ReaderError

    reader.read_at_least(min_len) fetches and returns an owned chunk containing at least min_len bytes. The returned chunk may be larger than min_len.

    If EOF is reached before enough data is fetched, UnexpectedEof will be raised. Any shorter trailing data remains buffered and can be fetched through another reader operation later.

    reader.read_at_least() is cancellation safe as long as the underlying reader implementation is cancellation safe. When it is cancelled, no data will be lost.

    ClientConnection::read_exactly

    async fn ClientConnection::read_exactly(self : ClientConnection, len : Int) -> Bytes raise
    ReaderError

    reader.read_exactly(len) reads exactly len bytes from the reader. It will wait until enough number of bytes is available. If EOF is reached before enough data is read, UnexpectedEof will be raised.

    ClientConnection::read_into

    reader.read_into(dst) reads at most dst.length() bytes from the reader into dst. The number of bytes actually read is returned. Note that the return value may be smaller than dst.length() if not enough data is immediately available. If EOF is reached and no more data is available, zero will be returned.

    ClientConnection::read_until

    async fn ClientConnection::read_until(self : ClientConnection, pattern : BytesView, include_delimiter? : Bool) -> Bytes? raise
    ReaderError

    reader.read_until(pat, include_delimiter? : Bool = false) reads content from reader until the byte string pat is found in the reader stream.

    If pat is found in the input stream, content before that occurrence is returned and the delimiter is consumed. If include_delimiter is true, pat itself is included at the end of the result. The returned data may be empty in this case if include_delimiter is false.

    EOF is implicitly treated as a delimiter by reader.read_until(). If pat is not found in the input stream when EOF is reached, trailing data before EOF will be returned (or None if there is no trailing data). In this case, the returned data contains no trailing delimiter even if include_delimiter=true. This can be used to detect the presence of trailing delimiter in the input stream.

    reader.read_until() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.read_until() is cancelled, no data will be lost.

    ClientConnection::request

    async fn ClientConnection::request(self : ClientConnection, meth : RequestMethod, path : StringView, extra_headers? : Map[CaseInsensitiveString, String]) -> Unit

    Send a HTTP request to the server. Only the header of the request will be sent, the request body can be sent through ClientConnection as an @io.BinaryWriter, or through client.text as an @io.TextWriter. Once request body has been sent, end_request must be called to complete the request and obtain response from the server.

    After performing a request, the next request MUST NOT be made before the request is completed via end_request.

    In addition to headers in ClientConnection::connect, extra HTTP headers can be passed via extra_headers. The following headers is automatically set by request, and must not be specified in extra_headers:

    • Host
    • Transfer-Encoding

    If Content-Length is present in extra_headers, it should be the total length of the request body. The request body can still be sent incrementally, but if the actual body being sent is shorter and longer than the provided length, an error will be raised.

    ClientConnection::skip_response_body

    async fn ClientConnection::skip_response_body(self : ClientConnection) -> Unit

    Skip the body of the response currently being produced, so that the next request can be made.

    ClientConnection::trailer

    Get the trailer of current response message.

    MUST be called AFTER all content of current message body has been read, and BEFORE reading the next response, otherwise this method will crash immediately.

    If the message is not chunk encoded, an empty header map will be returned.

    ClientConnection::write

    async fn ClientConnection::write(self : ClientConnection, data : BytesView) -> Unit raise
    WriterError

    writer.write(data) writes a chunk of data into the writer. write will ensure that all content of data has been written before returning. However, write only guarantees that all data is committed to the underlying writer object; it does not guarantee writer-specific properties, such as written data being flushed to persistent storage for a file stream.

    ClientConnection::write_reader

    Write data to the body of the request currently being sent. All writer API must be called after send_request. end_request must be called after all content of response body has been sent.

    Writing to @http.ClientConnection MAY be buffered, call flush manually to ensure data is delivered to the remote peer.
    pub struct Cookie {
    name : String
    value : String
    path : String?
    expires_raw : String?
    max_age : Int64?
    domain : String?
    secure : Bool
    http_only : Bool
    extensions : Array[String]
    } derive(
    Debug
    ,
    ToJson
    )

    A cookie value returned by a HTTP server via the Set-Cookie header

    Cookie::Cookie

    #alias(new, deprecated="`new` is deprecated, use `Cookie` instead")
    fn Cookie::Cookie(name : String, value : String, path? : String, expires_raw? : String, max_age? : Int64, domain? : String, secure? : Bool, http_only? : Bool, extensions? : Array[String]) -> Cookie

    Create a new cookie value

    MessageBody

    type MessageBody

    Type for collected HTTP message body

    MessageBody::binary

    fn MessageBody::binary(self : MessageBody) -> Bytes

    Return raw binary content of a HTTP message body

    MessageBody::json

    Decode a HTTP message body as UTF-8 encoded JSON

    MessageBody::text

    fn MessageBody::text(self : MessageBody) -> String raise

    Decode a HTTP message body as UTF-8 encoded text

    Proxy

    type Proxy

    Type for a HTTP/HTTPS proxy configuration. A Proxy object itself merely holds proxy configuration, it does not own any resource, and the same Proxy object can be reused for multiple requests.

    Proxy::Proxy

    fn Proxy::Proxy(url : StringView, username? : StringView, password? : StringView) -> Proxy

    Create a simple proxy from a proxy server URL. The proxy will perform a plain CONNECT to the proxy server.

    If username or password is present, HTTP Basic proxy authentication is used. An omitted username or password is encoded as an empty string.

    Proxy::custom_tunnel

    fn Proxy::custom_tunnel(f : async (StringView, UInt16) -> ClientConnection) -> Proxy

    Create a HTTP proxy by specifying a custom tunnel setup function. The callback receive the target hostname and port number to connect to, and should return a client connection in passthrough mode (see @http.ClientConnection::passthrough for more details). Usually, the callback should perform some custom handshake/authentication and perform a CONNECT request to the proxy server, and call enter_passthrough_mode() on succeess to setup a tunnel.

    RequestHeader

    pub struct RequestHeader {
    meth : RequestMethod
    path : String
    headers : Map[CaseInsensitiveString, String]
    } derive(
    Debug
    ,
    ToJson
    )

    HTTP request header

    RequestMethod

    pub(all) enum RequestMethod {
    Get
    Head
    Post
    Put
    Delete
    Connect
    Options
    Trace
    Patch
    Extension(String)
    } derive(Compare, Eq, Hash,
    Debug
    ,
    ToJson
    )

    HTTP request method

    RequestMethod::compare

    automatically derived

    RequestMethod::equal

    automatically derived

    RequestMethod::hash

    fn RequestMethod::hash(self : RequestMethod) -> Int
    automatically derived

    RequestMethod::to_string

    fn RequestMethod::to_string(self : RequestMethod) -> String

    ResponseHeader

    pub struct ResponseHeader {
    code : Int
    reason : String
    headers : Map[CaseInsensitiveString, String]
    cookies : Array[Cookie]
    } derive(
    Debug
    ,
    ToJson
    )

    HTTP response header

    Server

    type Server

    A HTTP server

    Server::Server

    #alias(new, deprecated="`new` is deprecated, use `Server` instead")
    async fn Server::Server(addr :
    Addr
    , dual_stack? : Bool, reuse_addr? : Bool, headers? : Map[CaseInsensitiveString, String]) -> Server

    Create a new HTTP server listening on addr.

    The meaning of dual_stack and reuse_addr is the same as @socket.TcpServer::new(), see there for more details.

    headers can be used to specify common headers shared by all responses sent by this server.

    Server::accept

    async fn Server::accept(self : Server) -> ServerConnection

    Accept a new connection from a HTTP server. The client address is available via the returned connection's .remote_addr() method.

    Server::close

    fn Server::close(self : Server) -> Unit

    Close a HTTP server, release associated resource

    Server::local_addr

    Get the actual listen address of a HTTP server

    Server::run_forever

    async fn Server::run_forever(self : Server, f : async (RequestHeader, ServerConnection) -> Unit, allow_failure? : Bool, max_connections? : Int) -> Unit

    Start the main loop of a HTTP server, the server will keep listening for new connections and new requests from existing connections. Requests are handled by the callback function f.

    • header of the request to process
    • a @http.ServerConnection that can be used to read request body or send response.

    Content of the incoming request body can be read streamingly using @io.BinaryReader interface (or @io.TextReader interface through the builtin .text view) on the @http.ServerConnection directly.

    The procedure to send a response is:
    1. initiate a response and send response header via .send_response()
    2. send the response body through @http.ServerConnection as an @io.BinaryWriter, or through .text as an @io.TextWriter
    3. (optional) complete the response via .end_response(). If .end_response() is not called, it will be called automatically after f returns.

    If allow_failure is true (true by default), error raised by f will not crash the whole server. In this case, run_forever will only terminate when cancelled externally. Note that if f fails, the connection used by f will still get aborted.

    If max_connections is present, at most max_connections clients are allowed in parallel. New clients will only get handled after a previous client terminates.

    If f fails without closing the connection, run_forever will close each connection automatically. If f manually closes the connection, the connection will be dropped after f returns. On error or cancellation, the server will be closed automatically.

    ServerConnection

    pub struct ServerConnection {
    text :
    Utf8TextView

    // private fields
    }

    A single HTTP server connection

    ServerConnection::ServerConnection

    #alias(new, deprecated="Use `ServerConnection(conn, headers=...)` instead")
    fn ServerConnection::ServerConnection(conn :
    Tcp
    , headers? : Map[CaseInsensitiveString, String]) -> ServerConnection

    Create a new HTTP server connection from a TCP connection.

    headers can be used to specify persistent headers for the connection, i.e. all response sent by this connection will share these headers. The following headers is automatically set, and must not be specified in headers:

    • Content-Length, Transfer-Encoding, Host

    ServerConnection::close

    fn ServerConnection::close(self : ServerConnection) -> Unit

    Close the connection, the underlying TCP connection will be closed as well. This function is idempotent: it is safe to call .close() multiple times, only the first .close() call takes effect.

    ServerConnection::drop_all

    Drop all remaining content from a binary reader, until EOF is reached.

    ServerConnection::drop_exactly

    async fn ServerConnection::drop_exactly(self : ServerConnection, len : Int) -> Unit raise
    ReaderError

    reader.drop_exactly(len) drops exactly len bytes from the reader. drop_exactly waits until enough bytes are available. If EOF is reached before enough data is dropped, UnexpectedEof will be raised.

    ServerConnection::end_response

    async fn ServerConnection::end_response(self : ServerConnection) -> Unit

    End the body of the response currently being sent. Should be called immediately after response body is fully sent.

    ServerConnection::enter_passthrough_mode

    async fn ServerConnection::enter_passthrough_mode(self : ServerConnection) -> Unit

    Let the server enter "pass through" mode, where the server serve as a TCP tunnel (maybe TLS encrypted) directly. This is useful for handling the special CONNECT HTTP request and HTTP protcol upgrade.

    In passthrough mode, Read/write the server becomes direct read/write on the underlying connection, and only its @io.BinaryReader and @io.BinaryWriter APIs may be used.

    When entering pass through mode, the server must be in a clean state (i.e. not in the middle of sending a response). Unread data from the body of the last request will be discarded.

    ServerConnection::flush_partial_data

    async fn ServerConnection::flush_partial_data(self : ServerConnection) -> Unit

    Flush all partial data and ensure they are delivered immediately. For writer transformers such as gzip writer, the underlying transport will be flushed as well. The flush is only best-effort: underlying implementation may choose to still buffer some data.

    flush_partial_data IS NOT used to ensure stream integrity: stream termination such as @tls.Tls::shutdown() is a protocol-specific operation. The only purpose of flush_partial_data is to ensure timely delivery of partial data. If the user only cares about eventual integrity of data, flush_partial_data is always UNNECESSARY.

    flush_partial_data mainly deal with userland buffering. It does not, for example, synchronize data to disk for a file system writer.

    ServerConnection::peek

    reader.peek() fetches and returns a chunk of data from the reader. The returned data will not get consumed from the reader: other reader API can still fetch them later.

    The chunk returned by reader.peek() is a copy-free slice of the reader's internal buffer, and its content will be overwritten by subsequent reader operations. So caller of peek MUST NOT use the returned slice after any other BinaryReader operation is invoked on the same reader. If the data need to be kept persistent, copy it via .to_owned().

    The returned chunk will contain at least one byte. If EOF is reached before any data is fetched, None will be returned.

    reader.peek() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.peek() is cancelled, no data will be lost.

    ServerConnection::peek_at_least

    async fn ServerConnection::peek_at_least(self : ServerConnection, min_len : Int) -> BytesView raise
    ReaderError

    reader.peek_at_least(min_len) fetches and returns a chunk containing at least min_len bytes without consuming it. The returned chunk may be larger than min_len.

    The returned view is valid only until another operation is invoked on the same reader. Use .to_owned() to keep the data persistently.

    If EOF is reached before enough data is fetched, UnexpectedEof will be raised. Any shorter trailing data remains buffered and can be fetched by a later reader operation.

    reader.peek_at_least() is cancellation safe as long as the underlying reader implementation is cancellation safe. When it is cancelled, no data will be lost.

    ServerConnection::peek_exactly

    async fn ServerConnection::peek_exactly(self : ServerConnection, len : Int) -> BytesView raise
    ReaderError

    reader.peek_exactly(len) fetches exactly len bytes from the reader. It will wait until enough number of bytes is available. The returned data will not get consumed from the reader: other reader API can still fetch them later.

    The chunk returned by reader.peek_exactly() is a copy-free slice of the reader's internal buffer, and its content will be overwritten by subsequent reader operations. So caller of peek MUST NOT use the returned slice after any other BinaryReader operation is invoked on the same reader. If the data need to be kept persistent, copy it via .to_owned().

    If EOF is reached before enough data is read, UnexpectedEof will be raised. In this case remaining data remain buffered, and can be fetched by other reader operations later.

    reader.peek_exactly() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.peek_exactly() is cancelled, no data will be lost.

    ServerConnection::peek_until

    async fn ServerConnection::peek_until(self : ServerConnection, pattern : BytesView, include_delimiter? : Bool) -> BytesView? raise
    ReaderError

    reader.peek_until(pat, include_delimiter? : Bool = false) fetches content from reader until the byte string pat is found in the reader stream. The returned data will not get consumed from the reader: other reader API can still fetch them later.

    The chunk returned by reader.peek_until() is a copy-free slice of the reader's internal buffer, and its content will be overwritten by subsequent reader operations. So caller of peek MUST NOT use the returned slice after any other BinaryReader operation is invoked on the same reader. If the data need to be kept persistent, copy it via .to_owned().

    If pat is found in the input stream, content before that occurrence is returned. If include_delimiter is true, pat itself is included at the end of the result. The returned data may be empty in this case if include_delimiter is false.

    EOF is implicitly treated as a delimiter by reader.peek_until(). If pat is not found in the input stream when EOF is reached, trailing data before EOF will be returned (or None if there is no trailing data). In this case, the returned data contains no trailing delimiter even if include_delimiter=true. This can be used to detect the presence of trailing delimiter in the input stream.

    reader.peek_until() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.peek_until() is cancelled, no data will be lost.

    ServerConnection::read

    reader.read() fetches and returns a chunk of data from the reader. It will return as fast as possible when new data become available.

    The returned chunk will contain at least one byte. If EOF is reached before any data is fetched, None will be returned.

    reader.read() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.read() is cancelled, no data will be lost.

    ServerConnection::read_all

    Read all remaining content from a binary reader, until EOF is reached.

    ServerConnection::read_at_least

    async fn ServerConnection::read_at_least(self : ServerConnection, min_len : Int) -> Bytes raise
    ReaderError

    reader.read_at_least(min_len) fetches and returns an owned chunk containing at least min_len bytes. The returned chunk may be larger than min_len.

    If EOF is reached before enough data is fetched, UnexpectedEof will be raised. Any shorter trailing data remains buffered and can be fetched through another reader operation later.

    reader.read_at_least() is cancellation safe as long as the underlying reader implementation is cancellation safe. When it is cancelled, no data will be lost.

    ServerConnection::read_exactly

    async fn ServerConnection::read_exactly(self : ServerConnection, len : Int) -> Bytes raise
    ReaderError

    reader.read_exactly(len) reads exactly len bytes from the reader. It will wait until enough number of bytes is available. If EOF is reached before enough data is read, UnexpectedEof will be raised.

    ServerConnection::read_into

    reader.read_into(dst) reads at most dst.length() bytes from the reader into dst. The number of bytes actually read is returned. Note that the return value may be smaller than dst.length() if not enough data is immediately available. If EOF is reached and no more data is available, zero will be returned.

    ServerConnection::read_request

    async fn ServerConnection::read_request(self : ServerConnection) -> RequestHeader

    Read a single request from the connection. If the body of the last request is not consumed yet, it will be discarded.

    After calling read_request, the body of the request can be obtained by using ServerConnection as an @io.BinaryReader, or through .text as an @io.TextReader.

    ServerConnection::read_until

    async fn ServerConnection::read_until(self : ServerConnection, pattern : BytesView, include_delimiter? : Bool) -> Bytes? raise
    ReaderError

    reader.read_until(pat, include_delimiter? : Bool = false) reads content from reader until the byte string pat is found in the reader stream.

    If pat is found in the input stream, content before that occurrence is returned and the delimiter is consumed. If include_delimiter is true, pat itself is included at the end of the result. The returned data may be empty in this case if include_delimiter is false.

    EOF is implicitly treated as a delimiter by reader.read_until(). If pat is not found in the input stream when EOF is reached, trailing data before EOF will be returned (or None if there is no trailing data). In this case, the returned data contains no trailing delimiter even if include_delimiter=true. This can be used to detect the presence of trailing delimiter in the input stream.

    reader.read_until() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.read_until() is cancelled, no data will be lost.

    ServerConnection::remote_addr

    Get the address of the remote client from a HTTP server connection

    ServerConnection::send_response

    async fn ServerConnection::send_response(self : ServerConnection, code : Int, reason : String, extra_headers? : Map[CaseInsensitiveString, String], cookies? : Array[Cookie]) -> Unit

    Send a response to the peer. The response body can then be sent through ServerConnection as an @io.BinaryWriter, or through .text as an @io.TextWriter. After calling send_response, end_response must be called before sending the next response.

    cookies, if present, specify a list of cookies that the server wish the client to set. They will be transferred to the client via the Set-Cookie HTTP header. Users should always set cookies via cookies instead of filling Set-Cookie header directly.

    If Content-Length is present in extra_headers, it should be the total length of the request body. This useful for, for example, file servers to allow clients to know the progress of download, perform multipart download etc.

    The request body can still be sent incrementally, but if the actual body being sent is shorter and longer than the provided length, an error will be raised.

    ServerConnection::skip_request_body

    async fn ServerConnection::skip_request_body(self : ServerConnection) -> Unit

    Manually discard the body of the request currently being processed.

    ServerConnection::trailer

    Get the trailer of current request message.

    MUST be called AFTER all content of current message body has been read, and BEFORE reading the next request, otherwise this method will crash immediately.

    If the message is not chunk encoded, an empty header map will be returned.

    ServerConnection::write

    async fn ServerConnection::write(self : ServerConnection, data : BytesView) -> Unit raise
    WriterError

    writer.write(data) writes a chunk of data into the writer. write will ensure that all content of data has been written before returning. However, write only guarantees that all data is committed to the underlying writer object; it does not guarantee writer-specific properties, such as written data being flushed to persistent storage for a file stream.

    ServerConnection::write_reader

    Write data to the body of the response currently being sent. Writer API must be called after send_response. end_response must be called after all content of response body has been sent.

    Writing to @http.ServerConnection MAY be buffered, call flush manually to ensure data is delivered to the remote peer.

    get

    async fn get(uri : StringView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a HTTP GET request to uri. Supported protocols are http:// and https://. The HTTP response message and the whole response body will be returned.

    proxy, if present, specifies the proxy to use for this request. See @http.ClientConnection::new for more details. proxy is not supported on JavaScript backend.

    See ClientConnection::request for more details.

    get_stream

    async fn get_stream(uri : StringView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, ClientConnection)

    Performs a GET request to the target URL. Return the response header and the connection assigned for this request. Response body can be obtained by reading from the connection via the @io.BinaryReader interface, or through the @io.TextReader interface using the builtin .text view on the connection. For requests with simple, short response message, @http.get_binary/@http.get_text/@http.get_json can be used to collect the body automatically.

    The returned connection must be manually closed via .close() after the caller no longer need to use it.

    post_binary

    async fn post_binary(uri : StringView, content : BytesView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Similar to get_binary, but performs a POST request instead.

    post_json

    async fn post_json(uri : StringView, content :
    Json
    , headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Similar to get_json, but performs a POST request instead.

    post_stream

    async fn post_stream(uri : StringView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> ClientConnection

    Performs a POST request to the target URL. Return the connection assigned for this request. Request body can be written through the @io.BinaryWriter interface on the connection, or through the @io.TextWriter interface using the builtin .text view on the connection.

    When the request body is completely written, end_request() should be called on the connection to terminate the request and obtain response header from the server. After receiving the response header, response body can be obtained by reading from the connection via the @io.BinaryReader interface, or through the @io.TextReader interface using the builtin .text view on the connection.

    For requests with simple, short message body, @http.post_binary/@http.post_text/@http.post_json can be used to collect the body automatically.

    The returned connection must be manually closed via .close() after the caller no longer need to use it.

    post_text

    async fn post_text(uri : StringView, content : StringView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Similar to get_text, but performs a POST request instead.

    put_binary

    async fn put_binary(uri : StringView, content : BytesView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Similar to get_binary, but performs a PUT request instead.

    put_json

    async fn put_json(uri : StringView, content :
    Json
    , headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Similar to get_json, but performs a PUT request instead.

    put_stream

    async fn put_stream(uri : StringView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> ClientConnection

    Performs a PUT request to the target URL. Return the connection assigned for this request. Request body can be written through the @io.BinaryWriter interface on the connection, or through the @io.TextWriter interface using the builtin .text view on the connection.

    When the request body is completely written, end_request() should be called on the connection to terminate the request and obtain response header from the server. After receiving the response header, response body can be obtained by reading from the connection via the @io.BinaryReader interface, or through the @io.TextReader interface using the builtin .text view on the connection.

    For requests with simple, short message body, @http.put_binary/@http.put_text/@http.put_json can be used to collect the body automatically.

    The returned connection must be manually closed via .close() after the caller no longer need to use it.

    put_text

    async fn put_text(uri : StringView, content : StringView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Similar to get_text, but performs a PUT request instead.

    request_binary

    async fn request_binary(meth : RequestMethod, uri : StringView, body : BytesView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a single HTTP request to uri with binary request body. Supported protocols are http:// and https://. The HTTP response message and the whole response body will be returned.

    proxy, if present, specifies the proxy to use for this request. See @http.ClientConnection(..) for more details. proxy is not supported on JavaScript backend.

    See ClientConnection::request for more details.

    request_json

    async fn request_json(meth : RequestMethod, uri : StringView, body :
    Json
    , headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a single HTTP request to uri with UTF-8 encoded JSON request body. Supported protocols are http:// and https://. The HTTP response message and the whole response body will be returned.

    proxy, if present, specifies the proxy to use for this request. See @http.ClientConnection(..) for more details. proxy is not supported on JavaScript backend.

    See ClientConnection::request for more details.

    request_stream

    async fn request_stream(meth : RequestMethod, uri : StringView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> ClientConnection

    Perform a generic HTTP request to uri. Return the connection assigned for this request. The caller should first write request body to the connection through the @io.BinaryWriter interface (or through the @io.TextWriter interface using the builtin .text view), then call .end_request() to finish the request and obtain server response, and finally read response message body through the @io.BinaryReader interface (or through the @io.TextReader interface using the builtin .text view) on the connection.

    The returned connection must be closed after finishing the request.

    For requests with short message body, @http.request_binary/@http.request_text/@http.request_json can be used to automatically collect request/response body.

    For common request methods, @http.get, @http.post etc. can be used instead.

    request_text

    async fn request_text(meth : RequestMethod, uri : StringView, body : StringView, headers? : Map[CaseInsensitiveString, String], proxy? : Proxy) -> (ResponseHeader, MessageBody)

    Perform a single HTTP request to uri with UTF-8 encoded request body. Supported protocols are http:// and https://. The HTTP response message and the whole response body will be returned.

    proxy, if present, specifies the proxy to use for this request. See @http.ClientConnection(..) for more details. proxy is not supported on JavaScript backend.

    See ClientConnection::request for more details.