location.rs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. use std::str::FromStr;
  2. use url::Url;
  3. pub struct ParsedRoute {
  4. pub(crate) url: url::Url,
  5. }
  6. impl ParsedRoute {
  7. pub(crate) fn new(url: Url) -> Self {
  8. Self { url }
  9. }
  10. // get the underlying url
  11. pub fn url(&self) -> &Url {
  12. &self.url
  13. }
  14. pub fn query(&self) -> Option<&String> {
  15. None
  16. }
  17. /// Returns the nth segment in the path. Paths that end with a slash have
  18. /// the slash removed before determining the segments. If the path has
  19. /// fewer segments than `n` then this method returns `None`.
  20. pub fn nth_segment(&self, n: usize) -> Option<&str> {
  21. self.url.path_segments()?.nth(n)
  22. }
  23. /// Returns the last segment in the path. Paths that end with a slash have
  24. /// the slash removed before determining the segments. The root path, `/`,
  25. /// will return an empty string.
  26. pub fn last_segment(&self) -> Option<&str> {
  27. self.url.path_segments()?.last()
  28. }
  29. /// Get the named parameter from the path, as defined in your router. The
  30. /// value will be parsed into the type specified by `T` by calling
  31. /// `value.parse::<T>()`. This method returns `None` if the named
  32. /// parameter does not exist in the current path.
  33. pub fn segment<T>(&self, name: &str) -> Option<&str>
  34. where
  35. T: FromStr,
  36. {
  37. self.url.path_segments()?.find(|&f| f.eq(name))
  38. }
  39. /// Get the named parameter from the path, as defined in your router. The
  40. /// value will be parsed into the type specified by `T` by calling
  41. /// `value.parse::<T>()`. This method returns `None` if the named
  42. /// parameter does not exist in the current path.
  43. pub fn parse_segment<T>(&self, name: &str) -> Option<Result<T, T::Err>>
  44. where
  45. T: FromStr,
  46. {
  47. self.url
  48. .path_segments()?
  49. .find(|&f| f.eq(name))
  50. .map(|f| f.parse::<T>())
  51. }
  52. }
  53. #[test]
  54. fn parses_location() {
  55. let route = ParsedRoute::new(Url::parse("app:///foo/bar?baz=qux&quux=corge").unwrap());
  56. }