Easily convert typed paths into URIs (#790)

* Easily convert typed paths into URIs

`#[derive(TypedPath)]` will now also generate `TryFrom<_> for Uri` for
easily converting paths into URIs for use with `Redirect` and friends.

Fixes https://github.com/tokio-rs/axum/issues/789

* Use a method on the `TypedPath` trait to convert to `Uri`

* fix doc ref

* Update changelogs
This commit is contained in:
David Pedersen
2022-02-28 09:58:22 +01:00
committed by GitHub
parent 67c385cd2d
commit da74084146
5 changed files with 45 additions and 2 deletions
+18
View File
@@ -1,4 +1,5 @@
use super::sealed::Sealed;
use http::Uri;
/// A type safe path.
///
@@ -87,6 +88,8 @@ use super::sealed::Sealed;
/// things, create links to known paths and have them verified statically. Note that the
/// [`Display`] implementation for each field must return something that's compatible with its
/// [`Deserialize`] implementation.
/// - A [`TryFrom<_> for Uri`](std::convert::TryFrom) implementation to converting your paths into
/// [`Uri`](axum::http::Uri).
///
/// Additionally the macro will verify the captures in the path matches the fields of the struct.
/// For example this fails to compile since the struct doesn't have a `team_id` field:
@@ -148,6 +151,21 @@ use super::sealed::Sealed;
pub trait TypedPath: std::fmt::Display {
/// The path with optional captures such as `/users/:id`.
const PATH: &'static str;
/// Convert the path into a `Uri`.
///
/// # Panics
///
/// The default implementation parses the required [`Display`] implemetation. If that fails it
/// will panic.
///
/// Using `#[derive(TypedPath)]` will never result in a panic since it percent-encodes
/// arguments.
///
/// [`Display`]: std::fmt::Display
fn to_uri(&self) -> Uri {
self.to_string().parse().unwrap()
}
}
/// Utility trait used with [`RouterExt`] to ensure the first element of a tuple type is a