Struct rocket::request::Form

source ·
pub struct Form<T>(pub T);
Expand description

A data guard for parsing FromForm types strictly.

This type implements the FromData trait. It provides a generic means to parse arbitrary structures from incoming form data.

§Strictness

A Form<T> will parse successfully from an incoming form only if the form contains the exact set of fields in T. Said another way, a Form<T> will error on missing and/or extra fields. For instance, if an incoming form contains the fields “a”, “b”, and “c” while T only contains “a” and “c”, the form will not parse as Form<T>. If you would like to admit extra fields without error, see LenientForm.

§Usage

This type can be used with any type that implements the FromForm trait. The trait can be automatically derived; see the FromForm documentation for more information on deriving or implementing the trait.

Because Form implements FromData, it can be used directly as a target of the data = "<param>" route parameter as long as its generic type implements the FromForm trait:

use rocket::request::Form;
use rocket::http::RawStr;

#[derive(FromForm)]
struct UserInput<'f> {
    // The raw, undecoded value. You _probably_ want `String` instead.
    value: &'f RawStr
}

#[post("/submit", data = "<user_input>")]
fn submit_task(user_input: Form<UserInput>) -> String {
    format!("Your value: {}", user_input.value)
}

A type of Form<T> automatically dereferences into an &T, though you can also transform a Form<T> into a T by calling into_inner(). Thanks to automatic dereferencing, you can access fields of T transparently through a Form<T>, as seen above with user_input.value.

For posterity, the owned analog of the UserInput type above is:

struct OwnedUserInput {
    // The decoded value. You _probably_ want this.
    value: String
}

A handler that handles a form of this type can similarly by written:

#[post("/submit", data = "<user_input>")]
fn submit_task(user_input: Form<OwnedUserInput>) -> String {
    format!("Your value: {}", user_input.value)
}

Note that no lifetime annotations are required in either case.

§&RawStr vs. String

Whether you should use a &RawStr or String in your FromForm type depends on your use case. The primary question to answer is: Can the input contain characters that must be URL encoded? Note that this includes common characters such as spaces. If so, then you must use String, whose FromFormValue implementation automatically URL decodes the value. Because the &RawStr references will refer directly to the underlying form data, they will be raw and URL encoded.

If it is known that string values will not contain URL encoded characters, or you wish to handle decoding and validation yourself, using &RawStr will result in fewer allocation and is thus preferred.

§Incoming Data Limits

The default size limit for incoming form data is 32KiB. Setting a limit protects your application from denial of service (DOS) attacks and from resource exhaustion through high memory consumption. The limit can be increased by setting the limits.forms configuration parameter. For instance, to increase the forms limit to 512KiB for all environments, you may add the following to your Rocket.toml:

[global.limits]
forms = 524288

Tuple Fields§

§0: T

Implementations§

source§

impl<T> Form<T>

source

pub fn into_inner(self) -> T

Consumes self and returns the parsed value.

§Example
use rocket::request::Form;

#[derive(FromForm)]
struct MyForm {
    field: String,
}

#[post("/submit", data = "<form>")]
fn submit(form: Form<MyForm>) -> String {
    form.into_inner().field
}

Trait Implementations§

source§

impl<T: Debug> Debug for Form<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T> Deref for Form<T>

source§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &T

Dereferences the value.
source§

impl<'f, T: FromForm<'f>> FromData<'f> for Form<T>

Parses a Form from incoming form data.

If the content type of the request data is not application/x-www-form-urlencoded, Forwards the request. If the form data cannot be parsed into a T, a Failure with status code UnprocessableEntity is returned. If the form string is malformed, a Failure with status code BadRequest is returned. Finally, if reading the incoming stream fails, returns a Failure with status code InternalServerError. In all failure cases, the raw form string is returned if it was able to be retrieved from the incoming stream.

All relevant warnings and errors are written to the console in Rocket logging format.

source§

type Error = FormDataError<'f, <T as FromForm<'f>>::Error>

The associated error to be returned when the guard fails.
source§

type Owned = String

The owned type returned from FromData::transform(). Read more
source§

type Borrowed = str

The borrowed type consumed by FromData::from_data() when FromData::transform() returns a Transform::Borrowed. Read more
source§

fn transform( request: &Request<'_>, data: Data, ) -> Transform<Outcome<Self::Owned, Self::Error>>

Transforms data into a value of type Self::Owned. Read more
source§

fn from_data( _: &Request<'_>, o: Transformed<'f, Self>, ) -> Outcome<Self, Self::Error>

Validates, parses, and converts the incoming request body data into an instance of Self. Read more
source§

impl<'q, T: FromForm<'q>> FromQuery<'q> for Form<T>

source§

type Error = <T as FromForm<'q>>::Error

The associated error to be returned if parsing/validation fails.
source§

fn from_query(q: Query<'q>) -> Result<Self, Self::Error>

Parses and validates an instance of Self from a query or returns an Error if parsing or validation fails.
source§

impl<'f, A, T: FromUriParam<Query, A> + FromForm<'f>> FromUriParam<Query, A> for Form<T>

source§

type Target = <T as FromUriParam<Query, A>>::Target

The resulting type of this conversion.
source§

fn from_uri_param(param: A) -> Self::Target

Converts a value of type T into a value of type Self::Target. The resulting value of type Self::Target will be rendered into a URI using its UriDisplay implementation.

Auto Trait Implementations§

§

impl<T> Freeze for Form<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Form<T>
where T: RefUnwindSafe,

§

impl<T> Send for Form<T>
where T: Send,

§

impl<T> Sync for Form<T>
where T: Sync,

§

impl<T> Unpin for Form<T>
where T: Unpin,

§

impl<T> UnwindSafe for Form<T>
where T: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T, I> AsResult<T, I> for T
where I: Input,

source§

fn as_result(self) -> Result<T, ParseErr<I>>

source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

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

§

impl<T> IntoCollection<T> for T

§

fn into_collection<A>(self) -> SmallVec<A>
where A: Array<Item = T>,

Converts self into a collection.
§

fn mapped<U, F, A>(self, f: F) -> SmallVec<A>
where F: FnMut(T) -> U, A: Array<Item = U>,

source§

impl<T> Same for T

source§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> Typeable for T
where T: Any,

source§

fn get_type(&self) -> TypeId

Get the TypeId of this object.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V