[−][src]Trait rocket::data::FromData
Trait implemented by data guards to derive a value from request body data.
Data Guards
A data guard is a request guard that operates on a request's body data.
Data guards validate, parse, and optionally convert request body data.
Validation and parsing/conversion is implemented through FromData. In
other words, every type that implements FromData is a data guard.
Data guards are used as the target of the data route attribute parameter.
A handler can have at most one data guard.
Example
In the example below, var is used as the argument name for the data guard
type T. When the submit route matches, Rocket will call the FromData
implemention for the type T. The handler will only be called if the guard
returns succesfully.
#[post("/submit", data = "<var>")] fn submit(var: T) -> ... { ... }
Outcomes
The returned Outcome of a from_data call
determines how the incoming request will be processed.
-
Success(S)
If the
OutcomeisSuccess, then theSuccessvalue will be used as the value for the data parameter. As long as all other parsed types succeed, the request will be handled by the requesting handler. -
Failure(Status, E)
If the
OutcomeisFailure, the request will fail with the given status code and error. The designated error Catcher will be used to respond to the request. Note that users can request types ofResult<S, E>andOption<S>to catchFailures and retrieve the error value. -
Forward(Data)
If the
OutcomeisForward, the request will be forwarded to the next matching request. This requires that no data has been read from theDataparameter. Note that users can request anOption<S>to catchForwards.
Provided Implementations
Rocket implements FromData for several built-in types. Their behavior is
documented here.
-
Data
The identity implementation; simply returns
Datadirectly.This implementation always returns successfully.
-
Option<T> where T: FromData
The type
Tis derived from the incoming data usingT'sFromDataimplementation. If the derivation is aSuccess, the dervived value is returned inSome. Otherwise, aNoneis returned.This implementation always returns successfully.
-
Result<T, T::Error> where T: FromData
The type
Tis derived from the incoming data usingT'sFromDataimplementation. If derivation is aSuccess, the value is returned inOk. If the derivation is aFailure, the error value is returned inErr. If the derivation is aForward, the request is forwarded. -
String
Reads the entire request body into a
String. If reading fails, returns aFailurewith the correspondingio::Error.WARNING: Do not use this implementation for anything but debugging. This is because the implementation reads the entire body into memory; since the user controls the size of the body, this is an obvious vector for a denial of service attack.
-
Vec<u8>
Reads the entire request body into a
Vec<u8>. If reading fails, returns aFailurewith the correspondingio::Error.WARNING: Do not use this implementation for anything but debugging. This is because the implementation reads the entire body into memory; since the user controls the size of the body, this is an obvious vector for a denial of service attack.
Example
Say that you have a custom type, Person:
struct Person { name: String, age: u16 }
Person has a custom serialization format, so the built-in Json type
doesn't suffice. The format is <name>:<age> with Content-Type: application/x-person. You'd like to use Person as a FromData type so
that you can retrieve it directly from a client's request body:
#[post("/person", data = "<person>")] fn person(person: Person) -> &'static str { "Saved the new person to the database!" }
A FromData implementation allowing this looks like:
use std::io::Read; use rocket::{Request, Data, Outcome}; use rocket::data::{self, FromData}; use rocket::http::{Status, ContentType}; use rocket::Outcome::*; impl FromData for Person { type Error = String; fn from_data(req: &Request, data: Data) -> data::Outcome<Self, String> { // Ensure the content type is correct before opening the data. let person_ct = ContentType::new("application", "x-person"); if req.content_type() != Some(&person_ct) { return Outcome::Forward(data); } // Read the data into a String. let mut string = String::new(); if let Err(e) = data.open().read_to_string(&mut string) { return Failure((Status::InternalServerError, format!("{:?}", e))); } // Split the string into two pieces at ':'. let (name, age) = match string.find(':') { Some(i) => (&string[..i], &string[(i + 1)..]), None => return Failure((Status::UnprocessableEntity, "':'".into())) }; // Parse the age. let age: u16 = match age.parse() { Ok(age) => age, Err(_) => return Failure((Status::UnprocessableEntity, "Age".into())) }; // Return successfully. Success(Person { name: name.into(), age: age }) } }
Associated Types
type Error
The associated error to be returned when the guard fails.
Required Methods
fn from_data(request: &Request, data: Data) -> Outcome<Self, Self::Error>
Validates, parses, and converts an instance of Self from the incoming
request body data.
If validation and parsing succeeds, an outcome of Success is returned.
If the data is not appropriate given the type of Self, Forward is
returned. If parsing fails, Failure is returned.
Implementations on Foreign Types
impl<T: FromData> FromData for Result<T, T::Error>[src]
impl<T: FromData> FromData for Result<T, T::Error>impl<T: FromData> FromData for Option<T>[src]
impl<T: FromData> FromData for Option<T>impl FromData for String[src]
impl FromData for Stringimpl FromData for Vec<u8>[src]
impl FromData for Vec<u8>Implementors
impl FromData for Data[src]
impl FromData for DataThe identity implementation of FromData. Always returns Success.
impl<'f, T: FromForm<'f>> FromData for Form<'f, T> where
T::Error: Debug, [src]
impl<'f, T: FromForm<'f>> FromData for Form<'f, T> where
T::Error: Debug, type Error = Option<String>
The raw form string, if it was able to be retrieved from the request.
fn from_data(request: &Request, data: Data) -> Outcome<Self, Self::Error>[src]
fn from_data(request: &Request, data: Data) -> Outcome<Self, Self::Error>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.
impl<'f, T: FromForm<'f>> FromData for LenientForm<'f, T> where
T::Error: Debug, [src]
impl<'f, T: FromForm<'f>> FromData for LenientForm<'f, T> where
T::Error: Debug, type Error = Option<String>
The raw form string, if it was able to be retrieved from the request.
fn from_data(request: &Request, data: Data) -> Outcome<Self, Self::Error>[src]
fn from_data(request: &Request, data: Data) -> Outcome<Self, Self::Error>Parses a LenientForm 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.