Trait rocket::request::FromParam

source ·
pub trait FromParam<'a>: Sized {
    type Error: Debug;

    // Required method
    fn from_param(param: &'a str) -> Result<Self, Self::Error>;
}
Expand description

Trait to convert a dynamic path segment string to a concrete value.

This trait is used by Rocket’s code generation facilities to parse dynamic path segment string values into a given type. That is, when a path contains a dynamic segment <param> where param has some type T that implements FromParam, T::from_param will be called.

§Deriving

The FromParam trait can be automatically derived for C-like enums. See FromParam derive for more information.

§Forwarding

If the conversion fails, the incoming request will be forwarded to the next matching route, if any. For instance, consider the following route and handler for the dynamic "/<id>" path:

#[get("/<id>")]
fn hello(id: usize) -> String {
    ...
}

If usize::from_param returns an Ok(usize) variant, the encapsulated value is used as the id function parameter. If not, the request is forwarded to the next matching route. Since there are no additional matching routes, this example will result in a 404 error for requests with invalid id values.

§Catching Errors

Sometimes, a forward is not desired, and instead, we simply want to know that the dynamic path segment could not be parsed into some desired type T. In these cases, types of Option<T>, Result<T, T::Error>, or Either<A, B> can be used, which implement FromParam themselves.

  • Option<T> where T: FromParam

    Always returns successfully.

    If the conversion to T fails, None is returned. If the conversion succeeds, Some(value) is returned.

  • Result<T, T::Error> where T: FromParam

    Always returns successfully.

    If the conversion to T fails, Err(error) is returned. If the conversion succeeds, Ok(value) is returned.

  • Either<A, B> where A: FromParam and B: FromParam

    Fails only when both A::from_param and B::from_param fail. If one of the two succeeds, the successful value is returned in Either::Left(A) or Either::Right(B) variant, respectively. If both fail, the error values from both calls are returned in a tuple in the Err variant.

Either<A, B> is particularly useful with a B type of &str, allowing you to retrieve the invalid path segment. Because &str’s implementation of FromParam always succeeds, the Right variant of the Either will always contain the path segment in case of failure.

For instance, consider the following route and handler:

use rocket::either::{Either, Left, Right};

#[get("/<id>")]
fn hello(id: Either<usize, &str>) -> String {
    match id {
        Left(id_num) => format!("usize: {}", id_num),
        Right(string) => format!("Not a usize: {}", string)
    }
}

In the above example, if the dynamic path segment cannot be parsed into a usize, the raw path segment is returned in the Right variant of the Either<usize, &str> value.

§Provided Implementations

Rocket implements FromParam for several standard library types. Their behavior is documented here.

    • Primitive types: f32, f64, isize, i8, i16, i32, i64, i128, usize, u8, u16, u32, u64, u128, bool
    • IpAddr and SocketAddr types: IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6, SocketAddr
    • NonZero* types: NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize

    A value is parsed successfully if the from_str method from the given type returns successfully. Otherwise, the raw path segment is returned in the Err value.

  • &str, String

    This implementation always returns successfully.

    Returns the percent-decoded path segment with invalid UTF-8 byte sequences replaced by � U+FFFD.

  • Option<T> where T: FromParam

    This implementation always returns successfully.

    The path segment is parsed by T’s FromParam implementation. If the parse succeeds, a Some(parsed_value) is returned. Otherwise, a None is returned.

  • Result<T, T::Error> where T: FromParam

    This implementation always returns successfully.

    The path segment is parsed by T’s FromParam implementation. The returned Result value is returned.

§Example

Say you want to parse a segment of the form:

[a-zA-Z]+:[0-9]+

into the following structure, where the string before the : is stored in key and the number after the colon is stored in value:

struct MyParam<'r> {
    key: &'r str,
    value: usize
}

The following implementation accomplishes this:

use rocket::request::FromParam;

impl<'r> FromParam<'r> for MyParam<'r> {
    type Error = &'r str;

    fn from_param(param: &'r str) -> Result<Self, Self::Error> {
        // We can convert `param` into a `str` since we'll check every
        // character for safety later.
        let (key, val_str) = match param.find(':') {
            Some(i) if i > 0 => (&param[..i], &param[(i + 1)..]),
            _ => return Err(param)
        };

        if !key.chars().all(|c| c.is_ascii_alphabetic()) {
            return Err(param);
        }

        val_str.parse()
            .map(|value| MyParam { key, value })
            .map_err(|_| param)
    }
}

With the implementation, the MyParam type can be used as the target of a dynamic path segment:

#[get("/<key_val>")]
fn hello(key_val: MyParam) -> String {
    ...
}

Required Associated Types§

source

type Error: Debug

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

Required Methods§

source

fn from_param(param: &'a str) -> Result<Self, Self::Error>

Parses and validates an instance of Self from a path parameter string or returns an Error if parsing or validation fails.

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl<'a> FromParam<'a> for &'a str

source§

type Error = Empty

source§

fn from_param(param: &'a str) -> Result<&'a str, Self::Error>

source§

impl<'a> FromParam<'a> for IpAddr

source§

type Error = <IpAddr as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for SocketAddr

source§

type Error = <SocketAddr as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for bool

source§

type Error = <bool as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for f32

source§

type Error = <f32 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for f64

source§

type Error = <f64 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for i8

source§

type Error = <i8 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for i16

source§

type Error = <i16 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for i32

source§

type Error = <i32 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for i64

source§

type Error = <i64 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for i128

source§

type Error = <i128 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for isize

source§

type Error = <isize as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for u8

source§

type Error = <u8 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for u16

source§

type Error = <u16 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for u32

source§

type Error = <u32 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for u64

source§

type Error = <u64 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for u128

source§

type Error = <u128 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for usize

source§

type Error = <usize as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for Ipv4Addr

source§

type Error = <Ipv4Addr as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for Ipv6Addr

source§

type Error = <Ipv6Addr as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for SocketAddrV4

source§

type Error = <SocketAddrV4 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for SocketAddrV6

source§

type Error = <SocketAddrV6 as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for PathBuf

source§

type Error = PathError

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroI8

source§

type Error = <NonZero<i8> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroI16

source§

type Error = <NonZero<i16> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroI32

source§

type Error = <NonZero<i32> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroI64

source§

type Error = <NonZero<i64> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroI128

source§

type Error = <NonZero<i128> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroIsize

source§

type Error = <NonZero<isize> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroU8

source§

type Error = <NonZero<u8> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroU16

source§

type Error = <NonZero<u16> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroU32

source§

type Error = <NonZero<u32> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroU64

source§

type Error = <NonZero<u64> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroU128

source§

type Error = <NonZero<u128> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'a> FromParam<'a> for NonZeroUsize

source§

type Error = <NonZero<usize> as FromStr>::Err

source§

fn from_param(param: &'a str) -> Result<Self, Self::Error>

source§

impl<'v, A: FromParam<'v>, B: FromParam<'v>> FromParam<'v> for Either<A, B>

Implements FromParam for Either<A, B>, where A and B both implement FromParam. If A::from_param returns Ok(a), Either::Left(a) is returned. If B::from_param returns Ok(b), Either::Right(b) is returned. If both A::from_param and B::from_param return Err(a) and Err(b), respectively, then Err((a, b)) is returned.

source§

type Error = (<A as FromParam<'v>>::Error, <B as FromParam<'v>>::Error)

source§

fn from_param(param: &'v str) -> Result<Self, Self::Error>

Implementors§

source§

impl<'a> FromParam<'a> for String

source§

impl<'a> FromParam<'a> for Uuid

Available on crate feature uuid only.
source§

impl<'a, T: FromParam<'a>> FromParam<'a> for Option<T>

source§

impl<'a, T: FromParam<'a>> FromParam<'a> for Result<T, T::Error>