product_os_request

Struct Response

Source
pub struct Response<T> { /* private fields */ }
Expand description

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<()>> {
    // ...
}

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:

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))
}

Or alternatively, serialize the body of a response to json

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))
}

Implementations§

Source§

impl Response<()>

Source

pub 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
let response = Response::builder()
    .status(200)
    .header("X-Custom-Foo", "Bar")
    .body(())
    .unwrap();
Source§

impl<T> Response<T>

Source

pub 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
let response = Response::new("hello world");

assert_eq!(response.status(), StatusCode::OK);
assert_eq!(*response.body(), "hello world");
Source

pub fn from_parts(parts: Parts, body: T) -> Response<T>

Creates a new Response with the given head and body

§Examples
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");
Source

pub fn status(&self) -> StatusCode

Returns the StatusCode.

§Examples
let response: Response<()> = Response::default();
assert_eq!(response.status(), StatusCode::OK);
Source

pub fn status_mut(&mut self) -> &mut StatusCode

Returns a mutable reference to the associated StatusCode.

§Examples
let mut response: Response<()> = Response::default();
*response.status_mut() = StatusCode::CREATED;
assert_eq!(response.status(), StatusCode::CREATED);
Source

pub fn version(&self) -> Version

Returns a reference to the associated version.

§Examples
let response: Response<()> = Response::default();
assert_eq!(response.version(), Version::HTTP_11);
Source

pub fn version_mut(&mut self) -> &mut Version

Returns a mutable reference to the associated version.

§Examples
let mut response: Response<()> = Response::default();
*response.version_mut() = Version::HTTP_2;
assert_eq!(response.version(), Version::HTTP_2);
Source

pub fn headers(&self) -> &HeaderMap

Returns a reference to the associated header field map.

§Examples
let response: Response<()> = Response::default();
assert!(response.headers().is_empty());
Source

pub fn headers_mut(&mut self) -> &mut HeaderMap

Returns a mutable reference to the associated header field map.

§Examples
let mut response: Response<()> = Response::default();
response.headers_mut().insert(HOST, HeaderValue::from_static("world"));
assert!(!response.headers().is_empty());
Source

pub fn extensions(&self) -> &Extensions

Returns a reference to the associated extensions.

§Examples
let response: Response<()> = Response::default();
assert!(response.extensions().get::<i32>().is_none());
Source

pub fn extensions_mut(&mut self) -> &mut Extensions

Returns a mutable reference to the associated extensions.

§Examples
let mut response: Response<()> = Response::default();
response.extensions_mut().insert("hello");
assert_eq!(response.extensions().get(), Some(&"hello"));
Source

pub fn body(&self) -> &T

Returns a reference to the associated HTTP body.

§Examples
let response: Response<String> = Response::default();
assert!(response.body().is_empty());
Source

pub fn body_mut(&mut self) -> &mut T

Returns a mutable reference to the associated HTTP body.

§Examples
let mut response: Response<String> = Response::default();
response.body_mut().push_str("hello world");
assert!(!response.body().is_empty());
Source

pub fn into_body(self) -> T

Consumes the response, returning just the body.

§Examples
let response = Response::new(10);
let body = response.into_body();
assert_eq!(body, 10);
Source

pub fn into_parts(self) -> (Parts, T)

Consumes the response returning the head and body parts.

§Examples
let response: Response<()> = Response::default();
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::OK);
Source

pub fn map<F, U>(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
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());

Trait Implementations§

Source§

impl<B> Body for Response<B>
where B: Body,

Source§

type Data = <B as Body>::Data

Values yielded by the Body.
Source§

type Error = <B as Body>::Error

The error type this Body might generate.
Source§

fn poll_frame( self: Pin<&mut Response<B>>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Frame<<Response<B> as Body>::Data>, <Response<B> as Body>::Error>>>

Attempt to pull out the next data buffer of this stream.
Source§

fn is_end_stream(&self) -> bool

Returns true when the end of stream has been reached. Read more
Source§

fn size_hint(&self) -> SizeHint

Returns the bounds on the remaining length of the stream. Read more
Source§

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

Source§

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

Returns a copy of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for Response<T>
where T: Debug,

Source§

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

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

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

Source§

fn default() -> Response<T>

Returns the “default value” for a type. Read more
Source§

impl<T> From<Response<T>> for BodyBytes
where T: Into<BodyBytes>,

Source§

fn from(value: Response<T>) -> BodyBytes

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<T> Freeze for Response<T>
where T: Freeze,

§

impl<T> !RefUnwindSafe for Response<T>

§

impl<T> Send for Response<T>
where T: Send,

§

impl<T> Sync for Response<T>
where T: Sync,

§

impl<T> Unpin for Response<T>
where T: Unpin,

§

impl<T> !UnwindSafe for Response<T>

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> BodyExt for T
where T: Body + ?Sized,

Source§

fn frame(&mut self) -> Frame<'_, Self>
where Self: Unpin,

Returns a future that resolves to the next Frame, if any.
Source§

fn map_frame<F, B>(self, f: F) -> MapFrame<Self, F>
where Self: Sized, F: FnMut(Frame<Self::Data>) -> Frame<B>, B: Buf,

Maps this body’s frame to a different kind.
Source§

fn map_err<F, E>(self, f: F) -> MapErr<Self, F>
where Self: Sized, F: FnMut(Self::Error) -> E,

Maps this body’s error value to a different value.
Source§

fn boxed(self) -> BoxBody<Self::Data, Self::Error>
where Self: Sized + Send + Sync + 'static,

Turn this body into a boxed trait object.
Source§

fn boxed_unsync(self) -> UnsyncBoxBody<Self::Data, Self::Error>
where Self: Sized + Send + 'static,

Turn this body into a boxed trait object that is !Sync.
Source§

fn collect(self) -> Collect<Self>
where Self: Sized,

Turn this body into Collected body which will collect all the DATA frames and trailers.
Source§

fn with_trailers<F>(self, trailers: F) -> WithTrailers<Self, F>
where Self: Sized, F: Future<Output = Option<Result<HeaderMap, Self::Error>>>,

Add trailers to the body. Read more
Source§

fn into_data_stream(self) -> BodyDataStream<Self>
where Self: Sized,

Turn this body into BodyDataStream.
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, dst: *mut T)

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

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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 = Infallible

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

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

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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more