diff --git a/src/request.rs b/src/request.rs index 8ca897442..99c7cb885 100644 --- a/src/request.rs +++ b/src/request.rs @@ -4,7 +4,7 @@ use std::{fmt, net}; use actix_http::http::{HeaderMap, Method, Uri, Version}; use actix_http::{Error, Extensions, HttpMessage, Message, Payload, RequestHead}; -use actix_router::{Path, Url}; +use actix_router::{Path, Url, ResourceDef}; use futures_util::future::{ok, Ready}; use tinyvec::TinyVec; @@ -135,6 +135,11 @@ impl HttpRequest { #[inline] pub fn match_pattern(&self) -> Option { self.0.rmap.match_pattern(self.path()) + + /// Checks if a given path matches a route + #[inline] + pub fn match_name(&self) -> Option<&ResourceDef> { + self.0.rmap.match_name(&self.path()) } /// Request extensions @@ -462,6 +467,27 @@ mod tests { ); } + #[test] + fn test_match_name() { + let mut rdef = ResourceDef::new("/index.html"); + *rdef.name_mut() = "index".to_string(); + + let mut rmap = ResourceMap::new(ResourceDef::new("")); + rmap.add(&mut rdef, None); + + assert!(rmap.has_resource("/index.html")); + + let req = TestRequest::with_uri("/test") + .header(header::HOST, "www.rust-lang.org") + .rmap(rmap) + .to_http_request(); + let route_name = req.resource_map().match_name("index").unwrap().name(); + assert_eq!( + route_name, + rdef.name() + ); + } + #[test] fn test_url_for_external() { let mut rdef = ResourceDef::new("https://youtube.com/watch/{video_id}"); diff --git a/src/rmap.rs b/src/rmap.rs index 0a0c96777..e0543e6cf 100644 --- a/src/rmap.rs +++ b/src/rmap.rs @@ -92,6 +92,12 @@ impl ResourceMap { } false } + /// Returns the full resource pattern matched against a route or None if no match is + /// found. + pub fn match_name(&self, path: &str) -> Option<&ResourceDef> { + let path = if path.is_empty() { "/" } else { path }; + self.named.get(path) + } /// Returns the full resource pattern matched against a path or None if no full match /// is possible.