Rocket/core/lib/src/local/request.rs

311 lines
9.7 KiB
Rust
Raw Normal View History

//! A structure representing a local request as created by [`Client`].
//!
//! # Usage
//!
//! A `LocalRequest` value is constructed via method constructors on [`Client`].
//! Headers can be added via the [`header`] builder method and the
//! [`add_header`] method. Cookies can be added via the [`cookie`] builder
//! method. The remote IP address can be set via the [`remote`] builder method.
//! The body of the request can be set via the [`body`] builder method or
//! [`set_body`] method.
//!
//! ## Example
//!
//! The following snippet uses the available builder methods to construct a
//! `POST` request to `/` with a JSON body:
//!
//! ```rust
//! use rocket::local::asynchronous::Client;
//! use rocket::http::{ContentType, Cookie};
//!
//! # rocket::async_test(async {
//! let client = Client::new(rocket::ignite()).await.expect("valid rocket");
//! let req = client.post("/")
//! .header(ContentType::JSON)
//! .remote("127.0.0.1:8000".parse().unwrap())
//! .cookie(Cookie::new("name", "value"))
//! .body(r#"{ "value": 42 }"#);
//! # });
//! ```
//!
//! # Dispatching
//!
//! A `LocalRequest` can be dispatched in one of two ways:
//!
//! 1. [`dispatch`]
//!
//! This method should always be preferred. The `LocalRequest` is consumed
//! and a response is returned.
//!
//! 2. [`mut_dispatch`]
//!
//! This method should _only_ be used when either it is known that the
//! application will not modify the request, or it is desired to see
//! modifications to the request. No cloning occurs, and the request is not
//! consumed.
//!
//! Additionally, note that `LocalRequest` implements `Clone`. As such, if the
//! same request needs to be dispatched multiple times, the request can first be
//! cloned and then dispatched: `request.clone().dispatch()`.
//!
//! [`Client`]: crate::local::asynchronous::Client
//! [`header`]: #method.header
//! [`add_header`]: #method.add_header
//! [`cookie`]: #method.cookie
//! [`remote`]: #method.remote
//! [`body`]: #method.body
//! [`set_body`]: #method.set_body
//! [`dispatch`]: #method.dispatch
//! [`mut_dispatch`]: #method.mut_dispatch
macro_rules! impl_request {
($import:literal $(@$prefix:tt $suffix:tt)? $name:ident) =>
{
impl<'c> $name<'c> {
/// Retrieves the inner `Request` as seen by Rocket.
///
/// # Example
///
/// ```rust
#[doc = $import]
/// use rocket::Request;
///
/// # Client::_test(|client| {
/// let client: Client = client;
/// let req = client.get("/");
/// let inner: &Request = req.inner();
/// # });
/// ```
#[inline(always)]
pub fn inner(&self) -> &Request<'c> {
self._request()
Overhaul URI types. This is fairly large commit with several entangled logical changes. The primary change in this commit is to completely overhaul how URI handling in Rocket works. Prior to this commit, the `Uri` type acted as an origin API. Its parser was minimal and lenient, allowing URIs that were invalid according to RFC 7230. By contrast, the new `Uri` type brings with it a strict RFC 7230 compliant parser. The `Uri` type now represents any kind of valid URI, not simply `Origin` types. Three new URI types were introduced: * `Origin` - represents valid origin URIs * `Absolute` - represents valid absolute URIs * `Authority` - represents valid authority URIs The `Origin` type replaces `Uri` in many cases: * As fields and method inputs of `Route` * The `&Uri` request guard is now `&Origin` * The `uri!` macro produces an `Origin` instead of a `Uri` The strict nature of URI parsing cascaded into the following changes: * Several `Route` methods now `panic!` on invalid URIs * The `Rocket::mount()` method is (correctly) stricter with URIs * The `Redirect` constructors take a `TryInto<Uri>` type * Dispatching of a `LocalRequest` correctly validates URIs Overall, URIs are now properly and uniformly handled throughout Rocket's codebase, resulting in a more reliable and correct system. In addition to these URI changes, the following changes are also part of this commit: * The `LocalRequest::cloned_dispatch()` method was removed in favor of chaining `.clone().dispatch()`. * The entire Rocket codebase uses `crate` instead of `pub(crate)` as a visibility modifier. * Rocket uses the `crate_visibility_modifier` and `try_from` features. A note on unsafety: this commit introduces many uses of `unsafe` in the URI parser. All of these uses are a result of unsafely transforming byte slices (`&[u8]` or similar) into strings (`&str`). The parser ensures that these casts are safe, but of course, we must label their use `unsafe`. The parser was written to be as generic and efficient as possible and thus can parse directly from byte sources. Rocket, however, does not make use of this fact and so would be able to remove all uses of `unsafe` by parsing from an existing `&str`. This should be considered in the future. Fixes #443. Resolves #263.
2018-07-29 01:26:15 +00:00
}
/// Add a header to this request.
///
/// Any type that implements `Into<Header>` can be used here. Among
/// others, this includes [`ContentType`] and [`Accept`].
///
/// [`ContentType`]: crate::http::ContentType
/// [`Accept`]: crate::http::Accept
///
/// # Examples
///
/// Add the Content-Type header:
///
/// ```rust
#[doc = $import]
/// use rocket::http::ContentType;
///
/// # Client::_test(|client| {
/// let client: Client = client;
/// let req = client.get("/").header(ContentType::JSON);
/// # });
/// ```
#[inline]
pub fn header<H>(mut self, header: H) -> Self
where H: Into<crate::http::Header<'static>>
{
self._request_mut().add_header(header.into());
self
}
/// Adds a header to this request without consuming `self`.
///
/// # Examples
///
/// Add the Content-Type header:
///
/// ```rust
#[doc = $import]
/// use rocket::http::ContentType;
///
/// # Client::_test(|client| {
/// let client: Client = client;
/// let mut req = client.get("/");
/// req.add_header(ContentType::JSON);
/// # });
/// ```
#[inline]
pub fn add_header<H>(&mut self, header: H)
where H: Into<crate::http::Header<'static>>
{
self._request_mut().add_header(header.into());
Overhaul URI types. This is fairly large commit with several entangled logical changes. The primary change in this commit is to completely overhaul how URI handling in Rocket works. Prior to this commit, the `Uri` type acted as an origin API. Its parser was minimal and lenient, allowing URIs that were invalid according to RFC 7230. By contrast, the new `Uri` type brings with it a strict RFC 7230 compliant parser. The `Uri` type now represents any kind of valid URI, not simply `Origin` types. Three new URI types were introduced: * `Origin` - represents valid origin URIs * `Absolute` - represents valid absolute URIs * `Authority` - represents valid authority URIs The `Origin` type replaces `Uri` in many cases: * As fields and method inputs of `Route` * The `&Uri` request guard is now `&Origin` * The `uri!` macro produces an `Origin` instead of a `Uri` The strict nature of URI parsing cascaded into the following changes: * Several `Route` methods now `panic!` on invalid URIs * The `Rocket::mount()` method is (correctly) stricter with URIs * The `Redirect` constructors take a `TryInto<Uri>` type * Dispatching of a `LocalRequest` correctly validates URIs Overall, URIs are now properly and uniformly handled throughout Rocket's codebase, resulting in a more reliable and correct system. In addition to these URI changes, the following changes are also part of this commit: * The `LocalRequest::cloned_dispatch()` method was removed in favor of chaining `.clone().dispatch()`. * The entire Rocket codebase uses `crate` instead of `pub(crate)` as a visibility modifier. * Rocket uses the `crate_visibility_modifier` and `try_from` features. A note on unsafety: this commit introduces many uses of `unsafe` in the URI parser. All of these uses are a result of unsafely transforming byte slices (`&[u8]` or similar) into strings (`&str`). The parser ensures that these casts are safe, but of course, we must label their use `unsafe`. The parser was written to be as generic and efficient as possible and thus can parse directly from byte sources. Rocket, however, does not make use of this fact and so would be able to remove all uses of `unsafe` by parsing from an existing `&str`. This should be considered in the future. Fixes #443. Resolves #263.
2018-07-29 01:26:15 +00:00
}
/// Set the remote address of this request.
///
/// # Examples
///
/// Set the remote address to "8.8.8.8:80":
///
/// ```rust
#[doc = $import]
///
/// # Client::_test(|client| {
/// let address = "8.8.8.8:80".parse().unwrap();
///
/// let client: Client = client;
/// let req = client.get("/").remote(address);
/// # });
/// ```
#[inline]
pub fn remote(mut self, address: std::net::SocketAddr) -> Self {
self._request_mut().set_remote(address);
self
}
/// Add a cookie to this request.
///
/// # Examples
///
/// Add `user_id` cookie:
///
/// ```rust
#[doc = $import]
/// use rocket::http::Cookie;
///
/// # Client::_test(|client| {
/// let client: Client = client;
/// let req = client.get("/")
/// .cookie(Cookie::new("username", "sb"))
/// .cookie(Cookie::new("user_id", "12"));
/// # });
/// ```
#[inline]
pub fn cookie(self, cookie: crate::http::Cookie<'_>) -> Self {
self._request().cookies().add_original(cookie.into_owned());
self
}
Remove Session in favor of private cookies. New testing API. Sessions -------- This commit removes the `Session` type in favor of methods on the `Cookies` types that allow for adding, removing, and getting private (signed and encrypted) cookies. These methods provide a superset of the functionality of `Session` while also being a minimal addition to the existing API. They can be used to implement the previous `Session` type as well as other forms of session storage. The new methods are: * Cookie::add_private(&mut self, Cookie) * Cookie::remove_private(&mut self, Cookie) * Cookie::get_private(&self, &str) Resolves #20 Testing ------- This commit removes the `rocket::testing` module. It adds the `rocket::local` module which provides a `Client` type for local dispatching of requests against a `Rocket` instance. This `local` package subsumes the previous `testing` package. Rocket Examples --------------- The `forms`, `optional_result`, and `hello_alt_methods` examples have been removed. The following example have been renamed: * extended_validation -> form_validation * hello_ranks -> ranking * from_request -> request_guard * hello_tls -> tls Other Changes ------------- This commit also includes the following smaller changes: * Config::{development, staging, production} constructors have been added for easier creation of default `Config` structures. * The `Config` type is exported from the root. * `Request` implements `Clone` and `Debug`. * `Request::new` is no longer exported. * A `Response::body_bytes` method was added to easily retrieve a response's body as a `Vec<u8>`.
2017-06-06 20:41:04 +00:00
/// Add all of the cookies in `cookies` to this request.
///
/// # Examples
///
/// Add `user_id` cookie:
///
/// ```rust
#[doc = $import]
/// use rocket::http::Cookie;
///
/// # Client::_test(|client| {
/// let client: Client = client;
/// let cookies = vec![Cookie::new("a", "b"), Cookie::new("c", "d")];
/// let req = client.get("/").cookies(cookies);
/// # });
/// ```
#[inline]
pub fn cookies(self, cookies: Vec<crate::http::Cookie<'_>>) -> Self {
for cookie in cookies {
self._request().cookies().add_original(cookie.into_owned());
}
Remove Session in favor of private cookies. New testing API. Sessions -------- This commit removes the `Session` type in favor of methods on the `Cookies` types that allow for adding, removing, and getting private (signed and encrypted) cookies. These methods provide a superset of the functionality of `Session` while also being a minimal addition to the existing API. They can be used to implement the previous `Session` type as well as other forms of session storage. The new methods are: * Cookie::add_private(&mut self, Cookie) * Cookie::remove_private(&mut self, Cookie) * Cookie::get_private(&self, &str) Resolves #20 Testing ------- This commit removes the `rocket::testing` module. It adds the `rocket::local` module which provides a `Client` type for local dispatching of requests against a `Rocket` instance. This `local` package subsumes the previous `testing` package. Rocket Examples --------------- The `forms`, `optional_result`, and `hello_alt_methods` examples have been removed. The following example have been renamed: * extended_validation -> form_validation * hello_ranks -> ranking * from_request -> request_guard * hello_tls -> tls Other Changes ------------- This commit also includes the following smaller changes: * Config::{development, staging, production} constructors have been added for easier creation of default `Config` structures. * The `Config` type is exported from the root. * `Request` implements `Clone` and `Debug`. * `Request::new` is no longer exported. * A `Response::body_bytes` method was added to easily retrieve a response's body as a `Vec<u8>`.
2017-06-06 20:41:04 +00:00
self
}
2017-06-30 09:06:03 +00:00
/// Add a [private cookie] to this request.
///
/// This method is only available when the `private-cookies` feature is
/// enabled.
///
/// [private cookie]: crate::http::Cookies::add_private()
///
/// # Examples
///
/// Add `user_id` as a private cookie:
///
/// ```rust
#[doc = $import]
/// use rocket::http::Cookie;
///
/// # Client::_test(|client| {
/// let client: Client = client;
/// let req = client.get("/").private_cookie(Cookie::new("user_id", "sb"));
/// # });
/// ```
#[inline]
#[cfg(feature = "private-cookies")]
pub fn private_cookie(self, cookie: crate::http::Cookie<'static>) -> Self {
self._request().cookies().add_original_private(cookie);
self
}
2017-06-30 09:06:03 +00:00
/// Set the body (data) of the request.
///
/// # Examples
///
/// Set the body to be a JSON structure; also sets the Content-Type.
///
/// ```rust
#[doc = $import]
/// use rocket::http::ContentType;
///
/// # Client::_test(|client| {
/// let client: Client = client;
/// let req = client.post("/")
/// .header(ContentType::JSON)
/// .body(r#"{ "key": "value", "array": [1, 2, 3], }"#);
/// # });
/// ```
#[inline]
pub fn body<S: AsRef<[u8]>>(mut self, body: S) -> Self {
// TODO: For CGI, we want to be able to set the body to be stdin
// without actually reading everything into a vector. Can we allow
// that here while keeping the simplicity? Looks like it would
// require us to reintroduce a NetStream::Local(Box<Read>) or
// something like that.
*self._body_mut() = body.as_ref().into();
self
}
2017-06-30 09:06:03 +00:00
/// Set the body (data) of the request without consuming `self`.
///
/// # Examples
///
/// Set the body to be a JSON structure; also sets the Content-Type.
///
/// ```rust
#[doc = $import]
/// use rocket::http::ContentType;
///
/// # Client::_test(|client| {
/// let client: Client = client;
/// let mut req = client.post("/").header(ContentType::JSON);
/// req.set_body(r#"{ "key": "value", "array": [1, 2, 3], }"#);
/// # });
/// ```
#[inline]
pub fn set_body<S: AsRef<[u8]>>(&mut self, body: S) {
*self._body_mut() = body.as_ref().into();
}
2017-06-30 09:06:03 +00:00
/// Dispatches the request, returning the response.
///
/// This method consumes `self` and is the preferred mechanism for
/// dispatching.
///
/// # Example
///
/// ```rust
/// use rocket::local::asynchronous::Client;
///
/// # rocket::async_test(async {
/// let client = Client::new(rocket::ignite()).await.unwrap();
/// let response = client.get("/").dispatch();
/// # });
/// ```
#[inline(always)]
pub $($prefix)? fn dispatch(self) -> LocalResponse<'c> {
self._dispatch()$(.$suffix)?
}
Remove Session in favor of private cookies. New testing API. Sessions -------- This commit removes the `Session` type in favor of methods on the `Cookies` types that allow for adding, removing, and getting private (signed and encrypted) cookies. These methods provide a superset of the functionality of `Session` while also being a minimal addition to the existing API. They can be used to implement the previous `Session` type as well as other forms of session storage. The new methods are: * Cookie::add_private(&mut self, Cookie) * Cookie::remove_private(&mut self, Cookie) * Cookie::get_private(&self, &str) Resolves #20 Testing ------- This commit removes the `rocket::testing` module. It adds the `rocket::local` module which provides a `Client` type for local dispatching of requests against a `Rocket` instance. This `local` package subsumes the previous `testing` package. Rocket Examples --------------- The `forms`, `optional_result`, and `hello_alt_methods` examples have been removed. The following example have been renamed: * extended_validation -> form_validation * hello_ranks -> ranking * from_request -> request_guard * hello_tls -> tls Other Changes ------------- This commit also includes the following smaller changes: * Config::{development, staging, production} constructors have been added for easier creation of default `Config` structures. * The `Config` type is exported from the root. * `Request` implements `Clone` and `Debug`. * `Request::new` is no longer exported. * A `Response::body_bytes` method was added to easily retrieve a response's body as a `Vec<u8>`.
2017-06-06 20:41:04 +00:00
}
Overhaul URI types. This is fairly large commit with several entangled logical changes. The primary change in this commit is to completely overhaul how URI handling in Rocket works. Prior to this commit, the `Uri` type acted as an origin API. Its parser was minimal and lenient, allowing URIs that were invalid according to RFC 7230. By contrast, the new `Uri` type brings with it a strict RFC 7230 compliant parser. The `Uri` type now represents any kind of valid URI, not simply `Origin` types. Three new URI types were introduced: * `Origin` - represents valid origin URIs * `Absolute` - represents valid absolute URIs * `Authority` - represents valid authority URIs The `Origin` type replaces `Uri` in many cases: * As fields and method inputs of `Route` * The `&Uri` request guard is now `&Origin` * The `uri!` macro produces an `Origin` instead of a `Uri` The strict nature of URI parsing cascaded into the following changes: * Several `Route` methods now `panic!` on invalid URIs * The `Rocket::mount()` method is (correctly) stricter with URIs * The `Redirect` constructors take a `TryInto<Uri>` type * Dispatching of a `LocalRequest` correctly validates URIs Overall, URIs are now properly and uniformly handled throughout Rocket's codebase, resulting in a more reliable and correct system. In addition to these URI changes, the following changes are also part of this commit: * The `LocalRequest::cloned_dispatch()` method was removed in favor of chaining `.clone().dispatch()`. * The entire Rocket codebase uses `crate` instead of `pub(crate)` as a visibility modifier. * Rocket uses the `crate_visibility_modifier` and `try_from` features. A note on unsafety: this commit introduces many uses of `unsafe` in the URI parser. All of these uses are a result of unsafely transforming byte slices (`&[u8]` or similar) into strings (`&str`). The parser ensures that these casts are safe, but of course, we must label their use `unsafe`. The parser was written to be as generic and efficient as possible and thus can parse directly from byte sources. Rocket, however, does not make use of this fact and so would be able to remove all uses of `unsafe` by parsing from an existing `&str`. This should be considered in the future. Fixes #443. Resolves #263.
2018-07-29 01:26:15 +00:00
impl std::fmt::Debug for $name<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self._request().fmt(f)
}
}
// TODO: Add test to check that `LocalRequest` is `Clone`.
}}