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:

  1. #[get("/hello/<name>")]
  2. fn hello(name: &RawStr) -> String {
  3. format!("Hello, {}!", name.as_str())
  4. }

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:

  1. #[get("/hello/<name>/<age>/<cool>")]
  2. fn hello(name: String, age: u8, cool: bool) -> String {
  3. if cool {
  4. format!("You're a cool {} year old, {}!", age, name)
  5. } else {
  6. format!("{}, we need to talk about your coolness.", name)
  7. }
  8. }

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).