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§
§impl<T> Response<T>
impl<T> Response<T>
pub fn new(body: T) -> Response<T>
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");
pub 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");
pub fn status(&self) -> StatusCode
pub fn status(&self) -> StatusCode
Returns the StatusCode
.
§Examples
let response: Response<()> = Response::default();
assert_eq!(response.status(), StatusCode::OK);
pub 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);
pub 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);
pub 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);
pub fn headers(&self) -> &HeaderMap
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());
pub fn headers_mut(&mut self) -> &mut HeaderMap
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());
pub 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());
pub 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"));
pub 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());
pub 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());
pub 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);
pub 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);
pub 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§
§impl<B> Body for Response<B>where
B: Body,
impl<B> Body for Response<B>where
B: Body,
§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>>>
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>>>
§fn is_end_stream(&self) -> bool
fn is_end_stream(&self) -> bool
true
when the end of stream has been reached. Read more§impl<Body> BodyExtractExt for Response<Body>
impl<Body> BodyExtractExt for Response<Body>
§async fn try_into_json<T>(self) -> Result<T, OpaqueError>where
T: DeserializeOwned + Send + 'static,
async fn try_into_json<T>(self) -> Result<T, OpaqueError>where
T: DeserializeOwned + Send + 'static,
§async fn try_into_string(self) -> Result<String, OpaqueError>
async fn try_into_string(self) -> Result<String, OpaqueError>
§impl<T> From<StaticResponseFactory<T>> for Response<Body>where
T: IntoResponse,
impl<T> From<StaticResponseFactory<T>> for Response<Body>where
T: IntoResponse,
§fn from(value: StaticResponseFactory<T>) -> Response<Body>
fn from(value: StaticResponseFactory<T>) -> Response<Body>
§impl<Body> HeaderValueGetter for Response<Body>
impl<Body> HeaderValueGetter for Response<Body>
§fn header_str<K>(&self, key: K) -> Result<&str, HeaderValueErr>where
K: AsHeaderName + Copy,
fn header_str<K>(&self, key: K) -> Result<&str, HeaderValueErr>where
K: AsHeaderName + Copy,
§fn header_bytes<K>(&self, key: K) -> Result<&[u8], HeaderValueErr>where
K: AsHeaderName + Copy,
fn header_bytes<K>(&self, key: K) -> Result<&[u8], HeaderValueErr>where
K: AsHeaderName + Copy,
§impl<B> IntoResponse for Response<B>
impl<B> IntoResponse for Response<B>
§fn into_response(self) -> Response<Body>
fn into_response(self) -> Response<Body>
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§
§impl<T> BodyExt for T
impl<T> BodyExt for T
§fn frame(&mut self) -> Frame<'_, Self> ⓘwhere
Self: Unpin,
fn frame(&mut self) -> Frame<'_, Self> ⓘwhere
Self: Unpin,
Frame
, if any.§fn boxed_unsync(self) -> UnsyncBoxBody<Self::Data, Self::Error>
fn boxed_unsync(self) -> UnsyncBoxBody<Self::Data, Self::Error>
§fn collect(self) -> Collect<Self> ⓘwhere
Self: Sized,
fn collect(self) -> Collect<Self> ⓘwhere
Self: Sized,
Collected
body which will collect all the DATA frames
and trailers.§fn with_trailers<F>(self, trailers: F) -> WithTrailers<Self, F>
fn with_trailers<F>(self, trailers: F) -> WithTrailers<Self, F>
§fn into_data_stream(self) -> BodyDataStream<Self>where
Self: Sized,
fn into_data_stream(self) -> BodyDataStream<Self>where
Self: Sized,
BodyDataStream
.source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§default unsafe fn clone_to_uninit(&self, dst: *mut T)
default unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)§impl<T> Conv for T
impl<T> Conv for T
§impl<T> FmtForward for T
impl<T> FmtForward for T
§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self
to use its Binary
implementation when Debug
-formatted.§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self
to use its Display
implementation when
Debug
-formatted.§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self
to use its LowerExp
implementation when
Debug
-formatted.§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self
to use its LowerHex
implementation when
Debug
-formatted.§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self
to use its Octal
implementation when Debug
-formatted.§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self
to use its Pointer
implementation when
Debug
-formatted.§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self
to use its UpperExp
implementation when
Debug
-formatted.§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self
to use its UpperHex
implementation when
Debug
-formatted.§fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
§impl<T> FutureExt for T
impl<T> FutureExt for T
§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more§impl<State, R> IntoEndpointService<State, ()> for R
impl<State, R> IntoEndpointService<State, ()> for R
§fn into_endpoint_service(
self,
) -> impl Service<State, Request<Body>, Response = Response<Body>, Error = Infallible>
fn into_endpoint_service( self, ) -> impl Service<State, Request<Body>, Response = Response<Body>, Error = Infallible>
rama_core::Service
.§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read more§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read more§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self
, then passes self.as_ref()
into the pipe function.§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self
, then passes self.as_mut()
into the pipe
function.§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self
, then passes self.deref()
into the pipe function.§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
§fn and<S, P, B, E>(self, other: P) -> And<T, P>
fn and<S, P, B, E>(self, other: P) -> And<T, P>
Policy
that returns Action::Follow
only if self
and other
return
Action::Follow
. Read more§impl<T> Tap for T
impl<T> Tap for T
§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B>
of a value. Read more§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B>
of a value. Read more§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R>
view of a value. Read more§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R>
view of a value. Read more§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target
of a value. Read more§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target
of a value. Read more§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap()
only in debug builds, and is erased in release builds.§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut()
only in debug builds, and is erased in release
builds.§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow()
only in debug builds, and is erased in release
builds.§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut()
only in debug builds, and is erased in release
builds.§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref()
only in debug builds, and is erased in release
builds.§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut()
only in debug builds, and is erased in release
builds.§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref()
only in debug builds, and is erased in release
builds.