[][src]Trait rocket::data::FromDataSimple

pub trait FromDataSimple: Sized {
    type Error;
    fn from_data(request: &Request, data: Data) -> Outcome<Self, Self::Error>;
}

A simple, less complex variant of FromData.

When transformation of incoming data isn't required, data guards should implement this trait instead of FromData. Any type that implements FromDataSimple automatically implements FromData. For a description of data guards, see the FromData documentation.

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 FromDataSimple implementation allowing this looks like:

use std::io::Read;

use rocket::{Request, Data, Outcome, Outcome::*};
use rocket::data::{self, FromDataSimple};
use rocket::http::{Status, ContentType};

// Always use a limit to prevent DoS attacks.
const LIMIT: u64 = 256;

impl FromDataSimple 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().take(LIMIT).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].to_string(), &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, age })
    }
}

Associated Types

The associated error to be returned when the guard fails.

Required Methods

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 FromDataSimple for String
[src]

impl FromDataSimple for Vec<u8>
[src]

Implementors