Struct rocket_http::hyper::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<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§
source§impl<B> Body for Response<B>where
B: Body,
impl<B> Body for Response<B>where B: Body,
source§fn poll_data(
self: Pin<&mut Response<B>>,
cx: &mut Context<'_>
) -> Poll<Option<Result<<Response<B> as Body>::Data, <Response<B> as Body>::Error>>>
fn poll_data( self: Pin<&mut Response<B>>, cx: &mut Context<'_> ) -> Poll<Option<Result<<Response<B> as Body>::Data, <Response<B> as Body>::Error>>>
source§fn poll_trailers(
self: Pin<&mut Response<B>>,
cx: &mut Context<'_>
) -> Poll<Result<Option<HeaderMap<HeaderValue>>, <Response<B> as Body>::Error>>
fn poll_trailers( self: Pin<&mut Response<B>>, cx: &mut Context<'_> ) -> Poll<Result<Option<HeaderMap<HeaderValue>>, <Response<B> as Body>::Error>>
HeaderMap
of trailers. Read moresource§fn is_end_stream(&self) -> bool
fn is_end_stream(&self) -> bool
true
when the end of stream has been reached. Read moresource§fn size_hint(&self) -> SizeHint
fn size_hint(&self) -> SizeHint
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§
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> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> IntoCollection<T> for T
impl<T> IntoCollection<T> for T
source§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere T: ?Sized,
source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the foreground set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red()
and
green()
, which have the same functionality but are
pithier.
Example
Set foreground color to white using fg()
:
use yansi::{Paint, Color};
painted.fg(Color::White);
Set foreground color to white using white()
.
use yansi::Paint;
painted.white();
source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightYellow
.
Example
println!("{}", value.bright_yellow());
source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightMagenta
.
Example
println!("{}", value.bright_magenta());
source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the background set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red()
and
on_green()
, which have the same functionality but
are pithier.
Example
Set background color to red using fg()
:
use yansi::{Paint, Color};
painted.bg(Color::Red);
Set background color to red using on_red()
.
use yansi::Paint;
painted.on_red();
source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightBlack
.
Example
println!("{}", value.on_bright_black());
source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightGreen
.
Example
println!("{}", value.on_bright_green());
source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightYellow
.
Example
println!("{}", value.on_bright_yellow());
source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightBlue
.
Example
println!("{}", value.on_bright_blue());
source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightMagenta
.
Example
println!("{}", value.on_bright_magenta());
source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightCyan
.
Example
println!("{}", value.on_bright_cyan());
source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightWhite
.
Example
println!("{}", value.on_bright_white());
source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute
value
.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold()
and
underline()
, which have the same functionality
but are pithier.
Example
Make text bold using attr()
:
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);
Make text bold using using bold()
.
use yansi::Paint;
painted.bold();
source§fn underline(&self) -> Painted<&T>
fn underline(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::Underline
.
Example
println!("{}", value.underline());
source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::RapidBlink
.
Example
println!("{}", value.rapid_blink());
source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi
Quirk
value
.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask()
and
wrap()
, which have the same functionality but are
pithier.
Example
Enable wrapping using .quirk()
:
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);
Enable wrapping using wrap()
.
use yansi::Paint;
painted.wrap();
source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition
value
applies. Replaces any previous condition.
See the crate level docs for more details.
Example
Enable styling painted
only when both stdout
and stderr
are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);