netio/http.rs#
Source: lib/netio/http.rs
http -- HTTP/1.1 messages and their wire format
Headers (case-insensitive names), Request, Response, Body
Reader: buffered reading of a Stream (lines, heads, bodies by Content-Length or chunked;
body_to hands a body over piece by piece)
write_response / write_request
Body::Upgrade(Upgrade): a 101 answer whose connection a protocol takes over (ws::Acceptor);
the server runs it on a thread of its own with the Upgraded connection
Limits: a message head of at most 16 KiB and 100 header lines, bodies up to the caller's
limit, chunk sizes checked before use.
MAX_HEAD: usize = 16 * 1024
MAX_HEADERS: usize = 100
struct Headers(pub Vec<(String, String)>)header lines; names compare case-insensitively
impl Headers
fn new() -> Headersfn get(&self, name: &str) -> Option<&str>fn set(&mut self, name: &str, value: &str)replace (or add) a headerfn add(&mut self, name: &str, value: &str)fn content_length(&self) -> Result<Option<u64>, ()>the Content-Length: Ok(None) without one, Err for a value that is not plain digits or headers that disagreefn remove(&mut self, name: &str)fn has_token(&self, name: &str, token: &str) -> boolwhether a comma-separated header contains a token (Connection: close, ...)struct Requesta request as the server sees it (and as the client sends it)method: Stringtarget: String-- path and query, as sent ("/api/jobs?limit=5")headers: Headersbody: Vec<u8>peer: Option<SocketAddr>-- the remote address (server side)client_id: Option<String>-- the identity the transport proved (TLS client certificate), if any
impl Request
fn new(method: &str, target: &str) -> Requestfn path(&self) -> &strthe path without the queryfn query(&self, key: &str) -> Option<String>a query parameter, decodedfn header(&self, name: &str) -> Option<&str>fn json(&self, limits: json::Limits) -> Option<Value>the body as JSON (None: not JSON or over the limits)fn bearer(&self) -> Option<&str>the bearer token of the Authorization headerenum Bodya response bodyEmptyBytes(Vec<u8>)Stream { len: Option<u64>, next: Box<dyn FnMut(&mut Vec<u8>) -> bool + Send> }-- produced piece by piece and sent chunked: the callback appends the next piece to the buffer and returns false after the last one (Content-Length whenlenis known)Upgrade(Upgrade)-- (G7d) with status 101: the server sends the head as it is (Connection and Upgrade as the handler set them, no length), then hands the connection to the upgrade on a thread of its own (ws::Acceptor::acceptmakes such answers). With any other status: no body
struct Upgrade(Box<dyn FnOnce(Upgraded) + Send>)(G7d) what takes over a connection after101 Switching Protocols(a WebSocket): runs once on a thread of the server's own, with the connection
impl Upgrade
fn new(f: impl FnOnce(Upgraded) + Send + 'static) -> Upgradethe code that takes over the connection (it ends the connection by returning)fn run(self, up: Upgraded)run it with the connection (the server does this)struct Upgraded(G7d) a connection after an upgrade, as the server hands it overstream: Box<dyn crate::Stream>-- the connection (TCP, or TLS underServer::start_with); reads and writes have no timeouts set, the protocol sets its ownbuffered: Vec<u8>-- bytes the client sent after its request that the server had already readpeer: Option<SocketAddr>-- the client's addressstop: Arc<AtomicBool>-- set when the server stops (Server::stopwaits for the upgraded connections to end)
struct Responsestatus: u16headers: Headersbody: Body
impl Response
fn new(status: u16) -> Responsefn bytes(status: u16, content_type: &str, body: Vec<u8>) -> Responsefn text(status: u16, s: &str) -> Responsefn json(status: u16, v: &Value) -> Responsefn header(mut self, name: &str, value: &str) -> Responsefn body_bytes(&self) -> &[u8]the body bytes (client side: always Bytes)fn body_json(&self, limits: json::Limits) -> Option<Value>fn reason(status: u16) -> &'static strthe reason phrase of a status codeenum ReadErrorwhy reading a message failedClosed-- the connection ended before a message started (normal end of keep-alive)Net(NetError)Bad-- malformed (400)HeadTooLarge-- head over 16 KiB or too many header lines (431)BodyTooLarge-- body over the limit (413)
struct Reader<'a>buffered reading of a stream
impl<'a> Reader<'a>
fn new(s: &'a dyn Stream) -> Reader<'a>fn set_min_rate(&mut self, rate: Option<(u32, u32)>)reads fail with TimedOut once fewer thanbytes_per_sarrived on average since this call, counted after a firstgrace_ms(a body that dribbles in a byte now and then, each within the stream's timeout, must not hold the reader for hours); None: no such limitfn set_deadline(&mut self, deadline_us: Option<u64>)reads fail with TimedOut once plat::time_us() is past this, and a read waits for bytes only until then (a limit for a whole head, where the stream's timeout counts each read)fn has_buffered(&self) -> boolwhether unread bytes are buffered (a pipelined next request)fn take_buffered(&mut self) -> Vec<u8>(G7d) the bytes read from the stream but not consumed yet, taken out of the reader (what came after a head that ended the HTTP part of a connection: a WebSocket's first frames)fn head(&mut self) -> Result<(String, Headers), ReadError>the start line and the headers of a messagefn body(&mut self, h: &Headers, max: usize, until_close: bool) -> Result<Vec<u8>, ReadError>a message body by Content-Length or chunked transfer (until_close: a response without either reads to the end)fn body_to(&mut self, h: &Headers, max: u64, until_close: bool, sink: &mut dyn FnMut(&[u8]) -> bool) -> Result<u64, ReadError>the body like body(), but each piece goes tosinkas it arrives (downloads of any size);sinkreturning false stops reading with Err(Bad) -> the number of body bytesfn write_response(s: &dyn Stream, r: &mut Response, head_only: bool, keep_alive: bool) -> boolsend a response;head_onlyfor HEAD requests; false when the connection brokefn write_switch(s: &dyn Stream, r: &Response) -> bool(G7d) send the head of a101 Switching Protocolsanswer as the handler built it (Connection, Upgrade and the protocol's headers; no length, no body); false when the connection brokefn write_request(s: &dyn Stream, method: &str, target: &str, h: &Headers, body: &[u8]) -> boolsend a request (the body as Content-Length)