Skip to main content

Response

Struct Response 

Source
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

Source

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);
Source

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"[..]));
Source

pub fn switching_protocols(protocol: &str) -> Self

A 101 Switching Protocols response handing the connection to protocol (for example websocket). The connection writes connection: upgrade and upgrade: <protocol>; add any protocol-specific headers (such as sec-websocket-accept) with header.

§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"[..]));
Source

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. Framing headers 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));
Source

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));
Source

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);
Source

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);
Source

pub fn close(self) -> Self

Closes the connection after this response.

§Examples
let r = http_net::Response::new(503).close();
assert!(r.closes());
Source

pub fn status(&self) -> u16

The status code.

§Examples
assert_eq!(http_net::Response::new(418).status(), 418);
Source

pub fn closes(&self) -> bool

Whether close was requested.

§Examples
assert!(!http_net::Response::new(200).closes());
Source

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(&[][..]));
Source

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 Clone for Response

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Response

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Response

Source§

impl PartialEq for Response

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Response

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.