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 422 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>
whereT: 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>
whereT: 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>
whereA: FromParam
andB: FromParam
Fails only when both
A::from_param
andB::from_param
fail. If one of the two succeeds, the successful value is returned inEither::Left(A)
orEither::Right(B)
variant, respectively. If both fail, the error values from both calls are returned in a tuple in theErr
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
andSocketAddr
types: IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6, SocketAddrNonZero*
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 theErr
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
’sFromParam
implementation. If the parse succeeds, aSome(parsed_value)
is returned. Otherwise, aNone
is returned. -
Result<T, T::Error> where T: FromParam
This implementation always returns successfully.
The path segment is parsed by
T
’sFromParam
implementation. The returnedResult
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 => (¶m[..i], ¶m[(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§
Required Methods§
Sourcefn from_param(param: &'a str) -> Result<Self, Self::Error>
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.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementations on Foreign Types§
Source§impl<'a> FromParam<'a> for SocketAddr
impl<'a> FromParam<'a> for SocketAddr
Source§impl<'a> FromParam<'a> for SocketAddrV4
impl<'a> FromParam<'a> for SocketAddrV4
Source§impl<'a> FromParam<'a> for SocketAddrV6
impl<'a> FromParam<'a> for SocketAddrV6
Source§impl<'a> FromParam<'a> for NonZeroI16
impl<'a> FromParam<'a> for NonZeroI16
Source§impl<'a> FromParam<'a> for NonZeroI32
impl<'a> FromParam<'a> for NonZeroI32
Source§impl<'a> FromParam<'a> for NonZeroI64
impl<'a> FromParam<'a> for NonZeroI64
Source§impl<'a> FromParam<'a> for NonZeroI128
impl<'a> FromParam<'a> for NonZeroI128
Source§impl<'a> FromParam<'a> for NonZeroIsize
impl<'a> FromParam<'a> for NonZeroIsize
Source§impl<'a> FromParam<'a> for NonZeroU16
impl<'a> FromParam<'a> for NonZeroU16
Source§impl<'a> FromParam<'a> for NonZeroU32
impl<'a> FromParam<'a> for NonZeroU32
Source§impl<'a> FromParam<'a> for NonZeroU64
impl<'a> FromParam<'a> for NonZeroU64
Source§impl<'a> FromParam<'a> for NonZeroU128
impl<'a> FromParam<'a> for NonZeroU128
Source§impl<'a> FromParam<'a> for NonZeroUsize
impl<'a> FromParam<'a> for NonZeroUsize
Source§impl<'v, A: FromParam<'v>, B: FromParam<'v>> FromParam<'v> for Either<A, B>
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.