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
sourceimpl<T> Response<T>
impl<T> Response<T>
sourcepub fn new(body: T) -> Response<T>
pub fn new(body: T) -> Response<T>
Creates a new blank Response
with the body
The component ports 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");
sourcepub fn from_parts(parts: Parts, body: T) -> Response<T>
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");
sourcepub fn status(&self) -> StatusCode
pub fn status(&self) -> StatusCode
Returns the StatusCode
.
Examples
let response: Response<()> = Response::default();
assert_eq!(response.status(), StatusCode::OK);
sourcepub fn status_mut(&mut self) -> &mut StatusCode
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);
sourcepub fn version(&self) -> Version
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);
sourcepub fn version_mut(&mut self) -> &mut Version
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);
sourcepub fn headers(&self) -> &HeaderMap<HeaderValue>
pub fn headers(&self) -> &HeaderMap<HeaderValue>
Returns a reference to the associated header field map.
Examples
let response: Response<()> = Response::default();
assert!(response.headers().is_empty());
sourcepub fn headers_mut(&mut self) -> &mut HeaderMap<HeaderValue>
pub fn headers_mut(&mut self) -> &mut HeaderMap<HeaderValue>
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());
sourcepub fn extensions(&self) -> &Extensions
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());
sourcepub fn extensions_mut(&mut self) -> &mut Extensions
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"));
sourcepub fn body(&self) -> &T
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());
sourcepub fn body_mut(&mut self) -> &mut T
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());
sourcepub fn into_body(self) -> T
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);
sourcepub fn into_parts(self) -> (Parts, T)
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);
sourcepub fn map<F, U>(self, f: F) -> Response<U> where
F: FnOnce(T) -> U,
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
sourceimpl<R: AsyncRead + Unpin> AsyncReadResponseExt<R> for Response<R>
impl<R: AsyncRead + Unpin> AsyncReadResponseExt<R> for Response<R>
sourcefn consume(&mut self) -> ConsumeFuture<'_, R>
fn consume(&mut self) -> ConsumeFuture<'_, R>
Read any remaining bytes from the response body stream and discard them until the end of the stream is reached. It is usually a good idea to call this method before dropping a response if you know you haven’t read the entire response body. Read more
sourcefn copy_to<'a, W>(&'a mut self, writer: W) -> CopyFuture<'a, R, W> where
W: AsyncWrite + Unpin + 'a,
fn copy_to<'a, W>(&'a mut self, writer: W) -> CopyFuture<'a, R, W> where
W: AsyncWrite + Unpin + 'a,
Copy the response body into a writer asynchronously. Read more
sourcefn bytes(&mut self) -> BytesFuture<'_, &mut R>
fn bytes(&mut self) -> BytesFuture<'_, &mut R>
Read the entire response body into memory. Read more
sourcefn text(&mut self) -> TextFuture<'_, &mut R>
fn text(&mut self) -> TextFuture<'_, &mut R>
text-decoding
only.Read the response body as a string asynchronously. Read more
sourcefn json<T>(&mut self) -> JsonFuture<'_, R, T> where
T: DeserializeOwned,
fn json<T>(&mut self) -> JsonFuture<'_, R, T> where
T: DeserializeOwned,
json
only.Deserialize the response body as JSON into a given type. Read more
sourceimpl<R: Read> ReadResponseExt<R> for Response<R>
impl<R: Read> ReadResponseExt<R> for Response<R>
sourcefn copy_to<W: Write>(&mut self, writer: W) -> Result<u64>
fn copy_to<W: Write>(&mut self, writer: W) -> Result<u64>
Copy the response body into a writer. Read more
sourcefn text(&mut self) -> Result<String>
fn text(&mut self) -> Result<String>
text-decoding
only.Read the response body as a string. Read more
sourcefn json<D>(&mut self) -> Result<D, Error> where
D: DeserializeOwned,
fn json<D>(&mut self) -> Result<D, Error> where
D: DeserializeOwned,
json
only.Deserialize the response body as JSON into a given type. Read more
sourceimpl<T> ResponseExt<T> for Response<T>
impl<T> ResponseExt<T> for Response<T>
sourcefn trailer(&self) -> &Trailer
fn trailer(&self) -> &Trailer
Get the trailer of the response containing headers that were received after the response body. Read more
sourcefn effective_uri(&self) -> Option<&Uri>
fn effective_uri(&self) -> Option<&Uri>
Get the effective URI of this response. This value differs from the original URI provided when making the request if at least one redirect was followed. Read more
sourcefn local_addr(&self) -> Option<SocketAddr>
fn local_addr(&self) -> Option<SocketAddr>
Get the local socket address of the last-used connection involved in this request, if known. Read more
sourcefn remote_addr(&self) -> Option<SocketAddr>
fn remote_addr(&self) -> Option<SocketAddr>
Get the remote socket address of the last-used connection involved in this request, if known. Read more
cookies
only.Get the configured cookie jar used for persisting cookies from this response, if any. Read more
Auto Trait Implementations
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
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Instruments this type with the provided Span
, returning an
Instrumented
wrapper. Read more
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
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
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
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
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more