pub struct Response(_);Expand description
An HTTP response.
An HTTP Response consists of a head (a status code and some headers), and a body (which may be empty). This type offers convenient helpers for constructing HTTP responses for you for common use-cases.
Examples
use under::{Request, Response, HttpEntity};
// Here, we're defining an endpoint for our server.
async fn handle_get(request: Request) -> Result<Response, anyhow::Error> {
let target = request.fragment_str("target").unwrap_or("world");
Ok(Response::text(format!("hello, {}", target)))
}
let mut http = under::http();
http
.at("/hello").get(handle_get)
.at("/hello/{target}").get(handle_get);
http.prepare();
let mut response = http.handle(Request::get("/hello")?).await?;
assert_eq!(response.status(), http::StatusCode::OK);
let body = response.data(512).into_text().await?;
assert_eq!(body, "hello, world");Implementations§
source§impl Response
impl Response
sourcepub fn empty_200() -> Self
pub fn empty_200() -> Self
Creates an empty response with a status code of 200.
See Response::empty_status for more information.
Example
let response = Response::empty_200();
assert_eq!(response.status(), http::StatusCode::OK);sourcepub fn empty_204() -> Self
pub fn empty_204() -> Self
Creates an empty response with a status code of 204.
See Response::empty_status for more information.
Examples
let response = Response::empty_204();
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);sourcepub fn empty_404() -> Self
pub fn empty_404() -> Self
Creates an empty response with a status code of 404.
See Response::empty_status for more information.
Examples
let response = Response::empty_404();
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);sourcepub fn empty_500() -> Self
pub fn empty_500() -> Self
Creates an empty response with a status code of 500.
See Response::empty_status for more information.
Examples
let response = Response::empty_500();
assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);sourcepub fn see_other<T>(location: T) -> Result<Self, Error>where
HeaderValue: TryFrom<T>,
<HeaderValue as TryFrom<T>>::Error: Into<Error>,
pub fn see_other<T>(location: T) -> Result<Self, Error>where
HeaderValue: TryFrom<T>,
<HeaderValue as TryFrom<T>>::Error: Into<Error>,
Creates a redirect (using See Other) to the given location.
Errors
This attempts to convert the location into a http::HeaderValue;
however, the conversion may fail (for reasons specified on
http::HeaderValue::from_str). It may also fail to construct the
underlying response.
Examples
let response = Response::see_other("/foo").unwrap();
assert_eq!(response.status(), http::StatusCode::SEE_OTHER);sourcepub fn permanent_redirect<T>(location: T) -> Result<Self, Error>where
HeaderValue: TryFrom<T>,
<HeaderValue as TryFrom<T>>::Error: Into<Error>,
pub fn permanent_redirect<T>(location: T) -> Result<Self, Error>where
HeaderValue: TryFrom<T>,
<HeaderValue as TryFrom<T>>::Error: Into<Error>,
Creates a permanent redirect to the given location.
Errors
This attempts to convert the location into a
http::HeaderValue; however, the conversion may fail (for
reasons specified on http::HeaderValue::from_str). It may also
fail to construct the underlying response.
Examples
let response = Response::permanent_redirect("/foo").unwrap();
assert_eq!(response.status(), http::StatusCode::PERMANENT_REDIRECT);sourcepub fn temporary_redirect<T>(location: T) -> Result<Self, Error>where
HeaderValue: TryFrom<T>,
<HeaderValue as TryFrom<T>>::Error: Into<Error>,
pub fn temporary_redirect<T>(location: T) -> Result<Self, Error>where
HeaderValue: TryFrom<T>,
<HeaderValue as TryFrom<T>>::Error: Into<Error>,
Creates a temporary redirect to the given location.
Errors
This attempts to convert the location into a
http::HeaderValue; however, the conversion may fail (for
reasons specified on http::HeaderValue::from_str). It may also
fail to construct the underlying response.
Examples
let response = Response::temporary_redirect("/foo").unwrap();
assert_eq!(response.status(), http::StatusCode::TEMPORARY_REDIRECT);sourcepub fn empty_status(status: StatusCode) -> Self
pub fn empty_status(status: StatusCode) -> Self
Creates a response with an empty body and a set status. The Content-Type is not set.
Examples
let response = Response::empty_status(http::StatusCode::NOT_FOUND);
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);sourcepub fn text<V: Into<String>>(body: V) -> Self
pub fn text<V: Into<String>>(body: V) -> Self
Creates a response with the given text body. The returned response
has a Content-Type of text/plain; charset=utf-8.
Examples
let response = Response::text("hello, world");sourcepub fn json<V: Serialize>(body: &V) -> Result<Self, Error>
pub fn json<V: Serialize>(body: &V) -> Result<Self, Error>
Creates a response with the given JSON body. The returned response
has a Content-Type of application/json; charset=utf-8.
Errors
This errors if the underlying JSON serialization fails; and it will return that exact error.
Examples
let response = Response::json(&serde_json::json!({ "hello": "world" }))?;sourcepub fn set_status<S: Into<StatusCode>>(&mut self, status: S)
pub fn set_status<S: Into<StatusCode>>(&mut self, status: S)
Sets the current responses’s status code.
Examples
let mut response = Response::empty_404();
response.set_status(http::StatusCode::OK);
assert_eq!(response.status(), http::StatusCode::OK);sourcepub fn with_status<S: Into<StatusCode>>(self, status: S) -> Self
pub fn with_status<S: Into<StatusCode>>(self, status: S) -> Self
Returns a response with the new status code.
Examples
let response = Response::empty_404();
let response = response.with_status(http::StatusCode::OK);
assert_eq!(response.status(), http::StatusCode::OK);sourcepub fn state<T: Send + Sync + 'static>(&self) -> Option<&T>
pub fn state<T: Send + Sync + 'static>(&self) -> Option<&T>
Returns state information provided by the
crate::middleware::StateMiddleware middleware. This is a
shortcut to retrieving the crate::middleware::State
extension from the response.
Examples
use under::middleware::State;
let mut response = Response::empty_200();
response.extensions_mut().insert(State(123u32));
assert_eq!(response.state::<u32>(), Some(&123u32));sourcepub fn ext<T: Send + Sync + 'static>(&self) -> Option<&T>
pub fn ext<T: Send + Sync + 'static>(&self) -> Option<&T>
Retrieves a specific extension from the extensions map. This is
the same as calling Self::extensions.get wit the given
type parameter.
Examples
let mut response = Response::empty_200();
assert_eq!(response.ext::<u32>(), None);sourcepub fn ext_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>
pub fn ext_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>
Retrieves a mutable reference to the specific extension from the
extensions map. This is the same as calling
Self::extensions_mut.get_mut with the given type
parameter.
Examples
let mut response = Response::empty_200();
assert_eq!(response.ext_mut::<u32>(), None);sourcepub fn set_ext<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self
pub fn set_ext<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self
Sets the value of the specific extension in the extensions map.
This is the same as calling Self::extensions_mut.insert
with the given parameter.
Examples
let mut response = Response::empty_200();
response.set_ext(123u32);
assert_eq!(response.ext::<u32>(), Some(&123u32));sourcepub fn with_ext<T: Send + Sync + 'static>(self, value: T) -> Self
pub fn with_ext<T: Send + Sync + 'static>(self, value: T) -> Self
Sets the value of the specific extension in the extensions map,
consuming self, and then returning the new value. This is
the same as calling Self::set_ext, but it consumes self.
Examples
let response = Response::empty_200();
let response = response.with_ext(123u32);
assert_eq!(response.ext::<u32>(), Some(&123u32));sourcepub fn remove_ext<T: Send + Sync + 'static>(&mut self) -> Option<T>
pub fn remove_ext<T: Send + Sync + 'static>(&mut self) -> Option<T>
Removes the specific extension from the extensions map. This is
the same as calling Self::extensions_mut.remove with the
given type parameter.
Examples
let mut response = Response::empty_200()
.with_ext(123u32);
assert_eq!(response.ext::<u32>(), Some(&123u32));
response.remove_ext::<u32>();
assert_eq!(response.ext::<u32>(), None);sourcepub fn without_ext<T: Send + Sync + 'static>(self) -> Self
pub fn without_ext<T: Send + Sync + 'static>(self) -> Self
Removes the specific extension from the extensions map,
consuming self, and then returning the removed value. This
is the same as calling Self::remove_ext, but it consumes
self.
Examples
let response = Response::empty_200()
.with_ext(123u32);
assert_eq!(response.ext::<u32>(), Some(&123u32));
let response = response.without_ext::<u32>();
assert_eq!(response.ext::<u32>(), None);sourcepub fn status(&self) -> StatusCode
pub fn status(&self) -> StatusCode
Returns the http::StatusCode.
Examples
let response = Response::default();
assert_eq!(response.status(), http::StatusCode::OK);sourcepub fn extensions(&self) -> &Extensions
pub fn extensions(&self) -> &Extensions
Returns a reference to the associated extensions.
Examples
let 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::default();
response.extensions_mut().insert("hello");
assert_eq!(response.extensions().get(), Some(&"hello"));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::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::default();
response.headers_mut().insert(HOST, HeaderValue::from_static("world"));
assert!(!response.headers().is_empty());Trait Implementations§
source§impl CookieExt for Response
impl CookieExt for Response
CookieMiddleware was not used), then this will return
None. Read moreCookieMiddleware was not used), then this will return
an empty cookie jar. Read moreself with the given cookie jar. This replaces (and drops)
the current cookie jar, if one exists. Read moreNone; if no cookie with the given name exists,
it returns None; otherwise, it returns its value. Read moreSelf::add_cookie.source§impl HttpEntity for Response
impl HttpEntity for Response
source§fn body_mut(&mut self) -> &mut Body
fn body_mut(&mut self) -> &mut Body
HasBody. Read moresource§fn headers(&self) -> &HeaderMap<HeaderValue>
fn headers(&self) -> &HeaderMap<HeaderValue>
source§fn headers_mut(&mut self) -> &mut HeaderMap<HeaderValue>
fn headers_mut(&mut self) -> &mut HeaderMap<HeaderValue>
source§fn set_body<I: Into<Body>>(&mut self, body: I) -> &mut Self
fn set_body<I: Into<Body>>(&mut self, body: I) -> &mut Self
source§fn with_body<I: Into<Body>>(self, body: I) -> Self
fn with_body<I: Into<Body>>(self, body: I) -> Self
self. This causes the previous body to be dropped in place. Read moresource§fn take_body(&mut self) -> Body
fn take_body(&mut self) -> Body
source§fn set_json<V: Serialize>(&mut self, new_body: &V) -> Result<&mut Self, Error>
fn set_json<V: Serialize>(&mut self, new_body: &V) -> Result<&mut Self, Error>
json only.source§fn with_json<V: Serialize>(self, new_body: &V) -> Result<Self, Error>
fn with_json<V: Serialize>(self, new_body: &V) -> Result<Self, Error>
json only.self. Note that this does not update the
Content-Type; the caller is responsible for that. Read moresource§fn data(&mut self, limit: u64) -> DataStream
fn data(&mut self, limit: u64) -> DataStream
source§fn header<H: AsHeaderName>(&self, key: H) -> Option<&HeaderValue>
fn header<H: AsHeaderName>(&self, key: H) -> Option<&HeaderValue>
source§fn header_all<H: AsHeaderName>(&self, key: H) -> GetAll<'_, HeaderValue>
fn header_all<H: AsHeaderName>(&self, key: H) -> GetAll<'_, HeaderValue>
source§fn set_header<H, V>(&mut self, key: H, value: V) -> Result<(), Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
fn set_header<H, V>(&mut self, key: H, value: V) -> Result<(), Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
source§fn with_header<H, V>(self, key: H, value: V) -> Result<Self, Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
fn with_header<H, V>(self, key: H, value: V) -> Result<Self, Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
self and returning a new version
with the given header. This can be useful for builder patterns.
Otherwise, this acts the same as Self::set_header.source§fn add_header<H, V>(&mut self, key: H, value: V) -> Result<(), Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
fn add_header<H, V>(&mut self, key: H, value: V) -> Result<(), Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
source§fn with_add_header<H, V>(self, key: H, value: V) -> Result<Self, Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
fn with_add_header<H, V>(self, key: H, value: V) -> Result<Self, Error>where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<<V as TryInto<HeaderValue>>::Error>,
self and returning a new version
with the given header. This can be useful for builder patterns.
Otherwise, this acts the same as Self::add_header.source§fn content_type(&self) -> Option<Mime>
fn content_type(&self) -> Option<Mime>
Content-Type header of the request, and parsed into
a mime; if the header does not exist, or is not a proper mime type,
this will return None. Read moresource§fn as_sniff<'life0, 'async_trait, T>(
&'life0 mut self,
limit: u64
) -> Pin<Box<dyn Future<Output = Result<T, UnderError>> + Send + 'async_trait>>where
T: 'async_trait + DeserializeOwned,
Self: Send + 'async_trait,
'life0: 'async_trait,
fn as_sniff<'life0, 'async_trait, T>(
&'life0 mut self,
limit: u64
) -> Pin<Box<dyn Future<Output = Result<T, UnderError>> + Send + 'async_trait>>where
T: 'async_trait + DeserializeOwned,
Self: Send + 'async_trait,
'life0: 'async_trait,
serde only.json,
cbor, msgpack). If the content-type is one of those, it forwards
the call to the respective functions (DataStream::into_json,
[DataStream::into_cbor], [DataStream::into_msgpack]), thereby
consuming the body. If it cannot find the content type, or the content
type is not one of those, it will return an error. Read moresource§fn as_sniff_form<'life0, 'async_trait, T>(
&'life0 mut self,
limit: u64
) -> Pin<Box<dyn Future<Output = Result<T, UnderError>> + Send + 'async_trait>>where
T: 'async_trait + DeserializeOwned + FromForm,
Self: Send + 'async_trait,
'life0: 'async_trait,
fn as_sniff_form<'life0, 'async_trait, T>(
&'life0 mut self,
limit: u64
) -> Pin<Box<dyn Future<Output = Result<T, UnderError>> + Send + 'async_trait>>where
T: 'async_trait + DeserializeOwned + FromForm,
Self: Send + 'async_trait,
'life0: 'async_trait,
json,
cbor, msgpack), or x-www-form-urlencoded. If the content-type is
one of those, it forwards the call to the respective functions
(DataStream::into_json, [DataStream::into_cbor],
[DataStream::into_msgpack], DataStream::into_form), thereby
consuming the body. If it cannot find the content type, or the content
type is not one of those, it will return an error. Read more