Dynamic Segments
You can declare path segments as dynamic by using angle brackets around variable names in a route’s path. For example, if we want to say Hello! to anything, not just the world, we can declare a route like so:
#[get("/hello/<name>")]
fn hello(name: &RawStr) -> String {
format!("Hello, {}!", name.as_str())
}
If we were to mount the path at the root (.mount("/", routes![hello])
), then any request to a path with two non-empty segments, where the first segment is hello
, will be dispatched to the hello
route. For example, if we were to visit /hello/John
, the application would respond with Hello, John!
.
Any number of dynamic path segments are allowed. A path segment can be of any type, including your own, as long as the type implements the FromParam trait. Rocket implements FromParam
for many of the standard library types, as well as a few special Rocket types. For the full list of supplied implementations, see the FromParam API docs. Here’s a more complete route to illustrate varied usage:
#[get("/hello/<name>/<age>/<cool>")]
fn hello(name: String, age: u8, cool: bool) -> String {
if cool {
format!("You're a cool {} year old, {}!", age, name)
} else {
format!("{}, we need to talk about your coolness.", name)
}
}
Raw Strings
You may have noticed an unfamiliar RawStr type in the code example above. This is a special type, provided by Rocket, that represents an unsanitized, unvalidated, and undecoded raw string from an HTTP message. It exists to separate validated string inputs, represented by types such as String
, &str
, and Cow<str>
types, from unvalidated inputs, represented by &RawStr
. It provides helpful methods to convert the unvalidated string into a validated one.
Because &RawStr
implements FromParam, it can be used as the type of a dynamic segment, as in the example above. When used as the type of a dynamic segment, a RawStr
points to a potentially undecoded string. By contrast, a String
is guaranteed to be decoded. Which you should use depends on whether you want direct but potentially unsafe access to the string (&RawStr
), or safe access to the string at the cost of an allocation (String
).