Struct Response

struct Response<T> { ... }

Represents an HTTP response

An HTTP response consists of a head and a potentially optional body. The body component is generic, enabling arbitrary types to represent the HTTP body. For example, the body could be Vec<u8>, a Stream of byte chunks, or a value that has been deserialized.

Typically you'll work with responses on the client side as the result of sending a Request and on the server you'll be generating a Response to send back to the client.

Examples

Creating a Response to return

use http::{Request, Response, StatusCode};

fn respond_to(req: Request<()>) -> http::Result<Response<()>> {
    let mut builder = Response::builder()
        .header("Foo", "Bar")
        .status(StatusCode::OK);

    if req.headers().contains_key("Another-Header") {
        builder = builder.header("Another-Header", "Ack");
    }

    builder.body(())
}

A simple 404 handler

use http::{Request, Response, StatusCode};

fn not_found(_req: Request<()>) -> http::Result<Response<()>> {
    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .body(())
}

Or otherwise inspecting the result of a request:

use http::{Request, Response};

fn get(url: &str) -> http::Result<Response<()>> {
    // ...
# panic!()
}

let response = get("https://www.rust-lang.org/").unwrap();

if !response.status().is_success() {
    panic!("failed to get a successful response status!");
}

if let Some(date) = response.headers().get("Date") {
    // we've got a `Date` header!
}

let body = response.body();
// ...

Deserialize a response of bytes via json:

# extern crate serde;
# extern crate serde_json;
# extern crate http;
use http::Response;
use serde::de;

fn deserialize<T>(res: Response<Vec<u8>>) -> serde_json::Result<Response<T>>
    where for<'de> T: de::Deserialize<'de>,
{
    let (parts, body) = res.into_parts();
    let body = serde_json::from_slice(&body)?;
    Ok(Response::from_parts(parts, body))
}
#
# fn main() {}

Or alternatively, serialize the body of a response to json

# extern crate serde;
# extern crate serde_json;
# extern crate http;
use http::Response;
use serde::ser;

fn serialize<T>(res: Response<T>) -> serde_json::Result<Response<Vec<u8>>>
    where T: ser::Serialize,
{
    let (parts, body) = res.into_parts();
    let body = serde_json::to_vec(&body)?;
    Ok(Response::from_parts(parts, body))
}
#
# fn main() {}

Implementations

impl Response<()>

fn builder() -> Builder

Creates a new builder-style object to manufacture a Response

This method returns an instance of Builder which can be used to create a Response.

Examples

# use http::*;
let response = Response::builder()
    .status(200)
    .header("X-Custom-Foo", "Bar")
    .body(())
    .unwrap();

impl<T> Response<T>

fn new(body: T) -> Response<T>

Creates a new blank Response with the body

The component parts of this response will be set to their default, e.g. the ok status, no headers, etc.

Examples

# use http::*;
let response = Response::new("hello world");

assert_eq!(response.status(), StatusCode::OK);
assert_eq!(*response.body(), "hello world");
fn from_parts(parts: Parts, body: T) -> Response<T>

Creates a new Response with the given head and body

Examples

# use http::*;
let response = Response::new("hello world");
let (mut parts, body) = response.into_parts();

parts.status = StatusCode::BAD_REQUEST;
let response = Response::from_parts(parts, body);

assert_eq!(response.status(), StatusCode::BAD_REQUEST);
assert_eq!(*response.body(), "hello world");
fn status(self: &Self) -> StatusCode

Returns the StatusCode.

Examples

# use http::*;
let response: Response<()> = Response::default();
assert_eq!(response.status(), StatusCode::OK);
fn status_mut(self: &mut Self) -> &mut StatusCode

Returns a mutable reference to the associated StatusCode.

Examples

# use http::*;
let mut response: Response<()> = Response::default();
*response.status_mut() = StatusCode::CREATED;
assert_eq!(response.status(), StatusCode::CREATED);
fn version(self: &Self) -> Version

Returns a reference to the associated version.

Examples

# use http::*;
let response: Response<()> = Response::default();
assert_eq!(response.version(), Version::HTTP_11);
fn version_mut(self: &mut Self) -> &mut Version

Returns a mutable reference to the associated version.

Examples

# use http::*;
let mut response: Response<()> = Response::default();
*response.version_mut() = Version::HTTP_2;
assert_eq!(response.version(), Version::HTTP_2);
fn headers(self: &Self) -> &HeaderMap<HeaderValue>

Returns a reference to the associated header field map.

Examples

# use http::*;
let response: Response<()> = Response::default();
assert!(response.headers().is_empty());
fn headers_mut(self: &mut Self) -> &mut HeaderMap<HeaderValue>

Returns a mutable reference to the associated header field map.

Examples

# use http::*;
# use http::header::*;
let mut response: Response<()> = Response::default();
response.headers_mut().insert(HOST, HeaderValue::from_static("world"));
assert!(!response.headers().is_empty());
fn extensions(self: &Self) -> &Extensions

Returns a reference to the associated extensions.

Examples

# use http::*;
let response: Response<()> = Response::default();
assert!(response.extensions().get::<i32>().is_none());
fn extensions_mut(self: &mut Self) -> &mut Extensions

Returns a mutable reference to the associated extensions.

Examples

# use http::*;
# use http::header::*;
let mut response: Response<()> = Response::default();
response.extensions_mut().insert("hello");
assert_eq!(response.extensions().get(), Some(&"hello"));
fn body(self: &Self) -> &T

Returns a reference to the associated HTTP body.

Examples

# use http::*;
let response: Response<String> = Response::default();
assert!(response.body().is_empty());
fn body_mut(self: &mut Self) -> &mut T

Returns a mutable reference to the associated HTTP body.

Examples

# use http::*;
let mut response: Response<String> = Response::default();
response.body_mut().push_str("hello world");
assert!(!response.body().is_empty());
fn into_body(self: Self) -> T

Consumes the response, returning just the body.

Examples

# use http::Response;
let response = Response::new(10);
let body = response.into_body();
assert_eq!(body, 10);
fn into_parts(self: Self) -> (Parts, T)

Consumes the response returning the head and body parts.

Examples

# use http::*;
let response: Response<()> = Response::default();
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::OK);
fn map<F, U>(self: Self, f: F) -> Response<U>
where
    F: FnOnce(T) -> U

Consumes the response returning a new response with body mapped to the return type of the passed in function.

Examples

# use http::*;
let response = Response::builder().body("some string").unwrap();
let mapped_response: Response<&[u8]> = response.map(|b| {
  assert_eq!(b, "some string");
  b.as_bytes()
});
assert_eq!(mapped_response.body(), &"some string".as_bytes());

impl<T> Any for Response<T>

fn type_id(self: &Self) -> TypeId

impl<T> Borrow for Response<T>

fn borrow(self: &Self) -> &T

impl<T> BorrowMut for Response<T>

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

impl<T> CloneToUninit for Response<T>

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

impl<T> Freeze for Response<T>

impl<T> From for Response<T>

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> RefUnwindSafe for Response<T>

impl<T> Send for Response<T>

impl<T> Sync for Response<T>

impl<T> ToOwned for Response<T>

fn to_owned(self: &Self) -> T
fn clone_into(self: &Self, target: &mut T)

impl<T> Unpin for Response<T>

impl<T> UnwindSafe for Response<T>

impl<T, U> Into for Response<T>

fn into(self: Self) -> U

Calls U::from(self).

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

impl<T, U> TryFrom for Response<T>

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

impl<T, U> TryInto for Response<T>

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

impl<T: $crate::clone::Clone> Clone for Response<T>

fn clone(self: &Self) -> Response<T>

impl<T: Default> Default for Response<T>

fn default() -> Response<T>

impl<T: fmt::Debug> Debug for Response<T>

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