Module std::net::http

HTTP server for handling web requests.

Provides a blocking HTTP server that listens on a TCP address, accepts incoming requests, and sends responses. Request-body reads time out after 30 seconds by default so slow trickle-feed clients cannot hold the server indefinitely.

Examples

import std.net.http;

fn main() {
    match http.listen(":8080") {
        .Ok(server) => {
            let req = server.accept();
            req.respond_text(200, "Hello from Hew!").expect("respond_text succeeds");
            req.close();
            server.close();
        }
        .Err(_err) => {
            println(http.listen_error());
        }
    }
}

Contents

Functions

Function server_port

pub fn server_port(server: Server) -> i64

Return the TCP port selected for this listener.

This is primarily useful after binding to port 0, which asks the kernel to choose an available ephemeral port.

Function listen_error

pub fn listen_error() -> string

Return the detail of this actor's most recent HTTP failure.

Reads the same runtime authority as http_client.last_error(); the name differs only because both files share one package pub-name namespace. Returns the empty string when the last HTTP call succeeded. Call it immediately after an Err from listen for the precise, non-secret reason.

Function listen

pub fn listen(addr: string) -> Result<Server, net.NetError>

Create a new HTTP server listening on the given address.

The address format is "host:port" or ":port" to listen on all interfaces.

Returns Err(net.NetError) when the address cannot be bound โ€” the port is already in use, the address is not local, or the string is not a valid endpoint. Use http.listen_error() for the precise detail.

Examples

import std.net;
import std.net.http;

fn main() {
    match http.listen("127.0.0.1:0") {
        .Ok(server) => server.close(),
        .Err(_) => println(f"listen failed"),
    }
}

Function respond

pub fn respond(req: Request, status: i64, content_type: string, body: string) -> Result<(), net.NetError>

Send a full HTTP response.

Function respond_text

pub fn respond_text(req: Request, status: i64, body: string) -> Result<(), net.NetError>

Send a plain-text HTTP response.

Function respond_json

pub fn respond_json(req: Request, status: i64, json: string) -> Result<(), net.NetError>

Send a JSON HTTP response.

Function respond_stream

pub fn respond_stream(req: Request, status: i64, content_type: string) -> Result<Sink<string>, net.NetError>

Begin a streaming HTTP response.

Types

Struct Server

An HTTP server bound to a TCP address.

Created by calling http.listen(addr), which returns Err when the address cannot be bound. Use accept() to wait for incoming requests in a loop, then call close() before the value goes out of scope.

Struct Request

An incoming HTTP request.

Obtained from server.accept(). Provides accessors for the request method, path, headers, and body. Must be responded to with one of the respond methods. Requests close automatically at scope exit; call close() to release one early.

Traits

Trait ServerMethods

Methods available on an HTTP Server.

Methods

fn accept(self: Self) -> Request

Block until a client connects and return the next Request.

fn set_request_timeout_ms(self: Self, timeout_ms: i64) -> i64

Set the per-request body read deadline in milliseconds.

Trait RequestMethods

Methods available on an HTTP Request.

Methods

fn method(self: Self) -> string

Return the HTTP method (e.g. "GET", "POST").

fn path(self: Self) -> string

Return the request path (e.g. "/api/users").

fn header(self: Self, name: string) -> string

Return the value of the named header, or an empty string.

fn headers(self: Self) -> Vec<(string, string)>

Return all request headers as a list of (name, value) pairs.

The returned vector is owned by the caller; Hew frees it automatically when it goes out of scope. Returns an empty vector if no headers were present or the request is invalid.

fn body(self: Self, encoding: string) -> string

Return the request body, decoded according to encoding.

Text is decoded as UTF-8. The encoding argument is reserved; binary data that is not UTF-8 cannot be returned as a string.

fn respond(self: Self, status: i64, content_type: string, body: string) -> Result<(), net.NetError>

Send a full HTTP response with status, content-type, and body.

The Content-Length header is derived from body automatically.

fn respond_text(self: Self, status: i64, body: string) -> Result<(), net.NetError>

Send a plain-text HTTP response.

Examples
import std.net.http;

fn main() {
    match http.listen(":8080") {
        .Ok(server) => {
            let req = server.accept();
            req.respond_text(200, "OK").expect("respond_text succeeds");
            req.close();
            server.close();
        }
        .Err(_err) => println(http.listen_error()),
    }
}
fn respond_json(self: Self, status: i64, json: string) -> Result<(), net.NetError>

Send a JSON HTTP response with Content-Type: application/json.

fn respond_stream(self: Self, status: i64, content_type: string) -> Result<Sink<string>, net.NetError>

Begin a streaming response and return a Sink for chunked output.

Each sink.send(chunk) sends data to the client immediately. Call sink.close() to finish the response.

Examples
import std.net.http;

fn main() {
    match http.listen(":8080") {
        .Ok(server) => {
            let req = server.accept();
            let body = req.respond_stream(200, "text/plain").expect("begin response");
            body.send("chunk 1").expect("send");
            body.send("chunk 2").expect("send");
            body.close();
            server.close();
        }
        .Err(_err) => println(http.listen_error()),
    }
}