Struct under::Response

source ·
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§

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

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

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

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

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

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

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

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

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");

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" }))?;

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

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

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

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

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

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

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

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

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

Returns the http::StatusCode.

Examples
let response = Response::default();
assert_eq!(response.status(), http::StatusCode::OK);

Returns a reference to the associated extensions.

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

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"));

Returns a reference to the associated header field map.

Examples
let response = Response::default();
assert!(response.headers().is_empty());

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§

Returns the extracted cookie jar. If no cookie jar had been extracted (i.e., the CookieMiddleware was not used), then this will return None. Read more
Returns the mutable cookie jar. If no cookie jar had been extracted (i.e. the CookieMiddleware was not used), then this will return an empty cookie jar. Read more
Returns self with the given cookie jar. This replaces (and drops) the current cookie jar, if one exists. Read more
Returns the value for the cookie with the given name. If no cookie jar is set, it returns None; if no cookie with the given name exists, it returns None; otherwise, it returns its value. Read more
Adds the given cookie to the current cookie jar. This addition does add to the delta, and creates the cookie jar if it does not exist. Read more
Adds the given cookie to the cookie jar. This is essentially the same as Self::add_cookie.
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Returns a mutable reference to the body of the request. This is used for all other methods in HasBody. Read more
Returns a reference to the associated header field map. Read more
Returns a mutable reference to the associated header field map. Read more
Sets the body of the request to the given body. This causes the previous body to be dropped in place. Read more
Sets the body of the request to the given body, consuming self. This causes the previous body to be dropped in place. Read more
Takes the body from this request, and replaces it with an empty body. The previous body is replaced with an empty body; thus, attempting to read the body more than once will cause successive attempts to fail. Read more
Available on crate feature json only.
Replaces the contents of the body with the given JSON body. Note that this does not update the Content-Type; the caller is responsible for that. Read more
Available on crate feature json only.
Replaces the contents of the body with the given JSON body, consuming self. Note that this does not update the Content-Type; the caller is responsible for that. Read more
Creates a data stream of the body. This consumes the body, and produces a stream that can then be read from. A limit must be provided, which is the maximum number of bytes that can be read from the stream. For most operations, exceeding this limit will cause an error. Read more
Retrieves the given header specified here. Read more
Retrieves all potential values for the given header specified here.
Sets the given header to the given value. If there already was a header, it is replaced with the given value. Read more
Sets the given header, consuming 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.
Sets the given header to the given value. If there already was a header, it is appended with the given value. Read more
Sets the given header, consuming 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.
Retrieves the content type of the body. This is normally pulled from the 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 more
Available on crate feature serde only.
Attempts to parse the body based off of the content-type header; currently, it can sniff any activated serde features (e.g. 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 more
Attempts to parse the body based off of the content type header; currently, it can sniff any activated serde features (e.g. 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
Converts the current type into a response. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

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

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more