Line data Source code
1 : use lazy_static::lazy_static;
2 : use regex_automata::util::captures::Captures;
3 : use regex_automata::meta::Regex;
4 :
5 : #[derive(Debug, PartialEq)]
6 : pub enum HttpProxyRoute {
7 : Streams { },
8 : Stream { stream_id: usize },
9 : }
10 :
11 : lazy_static! {
12 : static ref ROUTES: Regex = Regex::new_many(&[
13 : r"^/http/streams$",
14 : r"^/http/stream/(\d+)$",
15 : ]).unwrap();
16 : }
17 :
18 112 : pub fn parse_http_proxy_path(path: &str) -> Option<HttpProxyRoute> {
19 112 : let mut all = Captures::all(ROUTES.group_info().clone());
20 112 : ROUTES.captures(path, &mut all);
21 112 : match all.pattern().map(|p| p.as_usize()) {
22 : Some(0) => {
23 26 : Some(HttpProxyRoute::Streams { })
24 : }
25 : Some(1) => {
26 28 : let stream_id = path[all.get_group(1).unwrap()].parse().unwrap_or_default();
27 28 : Some(HttpProxyRoute::Stream { stream_id })
28 : }
29 : _ => {
30 58 : None
31 : }
32 : }
33 112 : }
34 :
35 : #[cfg(test)]
36 : mod test {
37 : use super::*;
38 : use anyhow::Result;
39 :
40 : #[tokio::test]
41 1 : async fn test_valid_routes() -> Result<()> {
42 1 : assert_eq!(parse_http_proxy_path("/http/streams"), Some(HttpProxyRoute::Streams { }));
43 1 : assert_eq!(parse_http_proxy_path("/http/stream/2"), Some(HttpProxyRoute::Stream { stream_id: 2 }));
44 1 : assert_eq!(parse_http_proxy_path("/http/stream/456"), Some(HttpProxyRoute::Stream { stream_id: 456 }));
45 2 : Ok(())
46 1 : }
47 :
48 : #[tokio::test]
49 1 : async fn test_invalid_routes() -> Result<()> {
50 1 : assert_eq!(parse_http_proxy_path("/http/foo"), None);
51 1 : assert_eq!(parse_http_proxy_path("/http/foo"), None);
52 1 : assert_eq!(parse_http_proxy_path("/http/streams/foo"), None);
53 1 : assert_eq!(parse_http_proxy_path("/http/stream/foo"), None);
54 1 : assert_eq!(parse_http_proxy_path("/http/stream/2/foo"), None);
55 2 : Ok(())
56 1 : }
57 : }
|