net::http
Enough HTTP to stand up a handler-based server and make client requests with no external dependencies. HTTP/1.1 with keep-alive lives here; HTTP/2 and WebSocket are the sibling modules net::http2 and net::ws.
public module net::http::method;
public module net::http::status;
public module net::http::headers;
public module net::http::request;
public module net::http::response;
public module net::http::conn;
public module net::http::router;
public module net::http::server;
public module net::http::client;
Everything here builds on the transports in net, so the same code runs over plaintext TCP or TLS. net::http re-exports each of its sub-modules, so import std::net::http; brings the whole layer into scope.
| File | What it holds | Import |
|---|---|---|
method | Method | import std::net::http::method; |
status | StatusCode | import std::net::http::status; |
headers | Headers, the case-insensitive map | import std::net::http::headers; |
request | Request | import std::net::http::request; |
response | Response | import std::net::http::response; |
conn | read_request / read_response on BufStream | import std::net::http::conn; |
router | Router, RouteKind | import std::net::http::router; |
server | HttpServer | import std::net::http::server; |
client | Client, send | import std::net::http::client; |
A server in one file
import std::net::http;
import std::future;
function hello(req: Request) -> Response {
return Response::text(StatusCode::ok(), Str::new("hi"));
}
function main() -> i32 {
mut router: Router = Router::new();
router.get(Str::new("/"), hello);
router.get(Str::new("/users/:id"), show_user);
mut server: HttpServer = HttpServer::with_router(addr, &router);
mut ex: Executor = Executor::new();
ex.block_on(server.run());
return 0;
}
A handler is a plain (Request) -> Response function pointer. The Router picks one by method and path; the HttpServer accepts connections and drives them. run() is async and needs an Executor.
public function name() { ... }
public:Visible to any module that imports this one - the default for top-level items and for struct fields, so it is mostly written to be explicit. public: opens a visibility block that groups the members after it.
public module collections::array;In a directory's _module.cryo aggregator, lists a submodule and whether it is public. Importing the directory's namespace sees only the modules declared public here.
namespace std::net::http::conn;HTTP/1.1 message framing over a buffered async connection.
module pagenamespace std::net::http::server;HTTP server: non-blocking, one connection at a time, HTTP/1.1 keep-alive within a connection.
module pageimport a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
namespace std::future;std::future: stackless async foundations — Future, Poll, Context, Waker, and the drivers that poll them.
function name<T>(param: Type) -> Ret { ... }Declares a function. Parameters are written name: Type and are never inferred; the return type follows -> and defaults to void. Declaration order does not matter: every signature is collected before any body is checked, so functions may call each other freely and recurse.
function hello(req: Request) -> Response(parameter) req: Requesttype struct Request {
method: Method;
path: String;
version: String;
headers: Headers;
body: Array<u8>;
params: HashMap<String, String>;
}HTTP request.
std::net::http::requesttype struct Response {
status: StatusCode;
version: String;
headers: Headers;
body: Array<u8>;
}HTTP response.
std::net::http::responsereturn value;Leaves the current function with the given value. A function whose return type is not void must return one; a bare return; is for void. In an async function it completes the future with the value.
static Response::text(status: StatusCode, body: Str) -> ResponseConvenience: Response::text(StatusCode::ok(), "hello") with Content-Type text/plain; charset=utf-8 and Content-Length set.
type struct StatusCode {
code: u16;
}static StatusCode::ok() -> StatusCodetype struct Str {
bytes: u8*;
length: u64;
}Str: a borrowed UTF-8 string slice.
std::collections::strstatic Str::new(text: string) -> StrConstruct from a NUL-terminated C-style string literal. The caller certifies that text is valid UTF-8 and outlives this view. The NUL terminator is not included in the view.
function main() -> i32mut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
mut router: Routertype struct Router {
routes: Array<Route>;
}Method- and path-based request dispatcher.
std::net::http::routerstatic Router::new() -> RouterCreate an empty router with no registered routes and built-in fallback handlers (plain-text 404 / 405).
std::net::http::routermut router: RouterRouter::get(mut &this, pattern: Str, handler: (Request) -> Response) -> &RouterRegister a GET exact route.
function hello(req: Request) -> Responsemut server: HttpServertype struct HttpServer {
addr: SocketAddr;
router: Router*;
read_timeout_secs: i64;
}A configured HTTP server ready to bind and run.
std::net::http::serverstatic HttpServer::with_router(addr: SocketAddr, router: mut &Router) -> HttpServerBuild a server backed by a Router. Pass &router; the router must outlive the server (declare both in the same scope).
mut ex: Executortype struct Executor {
inner: ExecInner*;
worker_tids: [u64];
}A multi-threaded, poll-driven task executor. Construct one, spawn futures onto it (keeping the JoinHandle to await a result, or dropping it to fire-and-forget), and block_on to drive a root future to its value. A pool of worker threads does all polling; the calling thread only ever blocks on a completion condvar.
static Executor::new() -> ExecutorCreate an executor whose pool is sized to the hardware parallelism.
std::future::executormut ex: ExecutorExecutor::block_on<F, O>(mut &this, root: F) -> O
where F: Future<O>Spawn root and block the calling thread until a worker drives it to completion, then return its value. Panics if root was cancelled or could not complete; use spawn(root).join() for the Result.
mut server: HttpServerasync HttpServer::run(mut &this) -> Result<(), IoError>Bind to this.addr and serve requests forever. Returns Err only on a fatal listener error (e.g. EMFILE, ENFILE).
type enum Method {
Get;
Head;
Post;
Put;
Delete;
Connect;
Options;
Trace;
Patch;
}HTTP method.
std::net::http::methodtype struct Headers {
inner: HashMap<String, String>;
}HTTP headers: case-insensitive name/value map.
std::net::http::headerstype struct BufStream<S> {
inner: S;
rbuf: Array<u8>;
rpos: u64;
scratch: Array<u8>;
wbuf: Array<u8>;
}type enum RouteKind {
Exact;
Prefix;
}Whether the route pattern must consume the entire request path or only a leading prefix.
std::net::http::routerasync function name(param: Type) -> T { ... }Compiles the function into a stackless state machine. Calling it builds a future whose output is the declared return type; nothing runs until that future is polled. Allowed on free functions, methods, and trait methods.
language reference