pub struct Response { /* private fields */ }Expand description
A response for a ServerConn to send.
The status line, content-length / transfer-encoding, and
connection are written by the connection, which knows the request’s
method and version: a HEAD request gets the headers without the body,
an HTTP/1.0 client never gets chunked encoding, and connection: close
is added whenever the connection will close.
§Examples
use http_net::Response;
let ok = Response::text(200, "hello");
assert_eq!(ok.status(), 200);
let asset = Response::new(200)
.header("content-type", "text/css")
.header("cache-control", "max-age=31536000, immutable")
.body(&b"body { margin: 0 }"[..]);
assert_eq!(asset.header_value("content-type"), Some(&b"text/css"[..]));Implementations§
Source§impl Response
impl Response
Sourcepub fn new(status: u16) -> Self
pub fn new(status: u16) -> Self
A response with this status, no extra headers, and an empty body.
The status is validated when the response is written (100..=599,
and only 101 among the 1xx codes).
§Examples
let r = http_net::Response::new(204);
assert_eq!(r.status(), 204);Sourcepub fn text(status: u16, text: &str) -> Self
pub fn text(status: u16, text: &str) -> Self
A text/plain; charset=utf-8 response with text as its body.
§Examples
let r = http_net::Response::text(404, "no such page");
assert_eq!(r.body_bytes(), Some(&b"no such page"[..]));Sourcepub fn from_error(error: &HttpError) -> Self
pub fn from_error(error: &HttpError) -> Self
The response a server sends after ServerConn::poll
returned a parse error: the status from HttpError::status (400
when it has none), a short text/plain body with the error’s
one-line description, and close. The text is static
and never includes the bytes that were refused.
§Examples
use http_net::{HttpError, Response, ServerConn};
let r = Response::from_error(&HttpError::HeadersTooLarge);
assert_eq!(r.status(), 431);
assert!(r.closes());
let mut conn = ServerConn::new();
let _ = conn.feed(b"GET / HTTP/1.1\r\n\r\n");
let err = conn.poll().unwrap_err();
let mut out = Vec::new();
conn.respond(&Response::from_error(&err), &mut out).unwrap();
assert!(out.starts_with(b"HTTP/1.1 400 Bad Request\r\n"));Sourcepub fn switching_protocols(protocol: &str) -> Self
pub fn switching_protocols(protocol: &str) -> Self
A 101 Switching Protocols response handing the connection to
protocol (for example websocket, or a name/version product
token). The connection writes connection: upgrade and
upgrade: <protocol>; add any protocol-specific headers (such as
sec-websocket-accept) with header.
The protocol must be one the request offered (RFC 9110 section 7.8),
compared ASCII case-insensitively; a name without a version matches
an offer of that name with any version. Otherwise, and always for
h2c (RFC 9113 section 3.1), writing it fails with
HttpError::UpgradeNotOffered. Writing it fails with
HttpError::InvalidState when the request is not a complete
upgrade request (RequestHead::is_upgrade
false, or its body not yet read), and with
HttpError::InvalidHeaderValue when protocol is not a token.
§Examples
let r = http_net::Response::switching_protocols("websocket")
.header("sec-websocket-accept", "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
assert_eq!(r.status(), 101);
assert_eq!(r.header_value("upgrade"), Some(&b"websocket"[..]));Sourcepub fn header(self, name: &str, value: impl AsRef<[u8]>) -> Self
pub fn header(self, name: &str, value: impl AsRef<[u8]>) -> Self
Adds a header field. The name must be a token and the value may not
contain control characters other than tab, nor leading or trailing
whitespace. The framing and hop-by-hop fields (content-length,
transfer-encoding, connection, upgrade, trailer, keep-alive,
proxy-connection, and te) are refused with
HttpError::ReservedHeader; the first problem is reported when the
response is written.
§Examples
use http_net::{HttpError, Response, ServerConn};
let bad = Response::new(200).header("content-length", "5");
let mut conn = ServerConn::new();
let _ = conn.feed(b"GET / HTTP/1.1\r\nHost: a\r\n\r\n");
let _ = conn.poll();
assert_eq!(conn.respond(&bad, &mut Vec::new()), Err(HttpError::ReservedHeader));Sourcepub fn body(self, body: impl Into<Cow<'static, [u8]>>) -> Self
pub fn body(self, body: impl Into<Cow<'static, [u8]>>) -> Self
Sets the whole body; it is sent with content-length. Static data
(an embedded asset) is borrowed rather than copied.
§Examples
static PAGE: &[u8] = b"<!doctype html><title>x</title>";
let r = http_net::Response::new(200).body(PAGE);
assert_eq!(r.body_bytes(), Some(PAGE));Sourcepub fn chunked(self) -> Self
pub fn chunked(self) -> Self
Streams the body with chunked encoding: after
ServerConn::respond, send data with
ServerConn::send_body and end it
with ServerConn::end_body. For an
HTTP/1.0 client the connection falls back to closing the connection
to end the body.
§Examples
let r = http_net::Response::new(200).chunked();
assert_eq!(r.body_bytes(), None);Sourcepub fn content_length(self, len: u64) -> Self
pub fn content_length(self, len: u64) -> Self
Streams a body of exactly len bytes, sent with content-length;
sending more or fewer is HttpError::BodyLengthMismatch.
§Examples
let r = http_net::Response::new(200).content_length(1 << 20);
assert_eq!(r.body_bytes(), None);Sourcepub fn close(self) -> Self
pub fn close(self) -> Self
Closes the connection after this response, unless it is a 101 or a
2xx to CONNECT, which hand the connection over.
§Examples
let r = http_net::Response::new(503).close();
assert!(r.closes());Sourcepub fn clear(&mut self, status: u16)
pub fn clear(&mut self, status: u16)
Resets the response to Response::new(status) while keeping the
allocation of its field storage, so one Response per connection
can be reused without allocating for every request. An owned body is
dropped.
§Examples
use http_net::Response;
let mut r = Response::new(200).header("x-request", "1").close();
r.clear(204);
assert_eq!(r.status(), 204);
assert_eq!(r.header_value("x-request"), None);
assert!(!r.closes());
r = r.header("x-request", "2"); // reuses the field storage
assert_eq!(r.header_value("x-request"), Some(&b"2"[..]));Sourcepub fn body_bytes(&self) -> Option<&[u8]>
pub fn body_bytes(&self) -> Option<&[u8]>
The full body, or None for a streamed one.
§Examples
assert_eq!(http_net::Response::new(200).body_bytes(), Some(&[][..]));Sourcepub fn header_value(&self, name: &str) -> Option<&[u8]>
pub fn header_value(&self, name: &str) -> Option<&[u8]>
The value of the first header named name added to this response
(ASCII case-insensitive), including the upgrade of
switching_protocols.
§Examples
let r = http_net::Response::new(200).header("x-id", "7");
assert_eq!(r.header_value("X-ID"), Some(&b"7"[..]));Trait Implementations§
Source§impl Debug for Response
Shows status, fields, body size, and flags; the values of credential
fields (set-cookie above all) are replaced by <redacted N bytes>.
impl Debug for Response
Shows status, fields, body size, and flags; the values of credential
fields (set-cookie above all) are replaced by <redacted N bytes>.