Skip to main content

aiway_protocol/context/
route.rs

1use crate::gateway::plugin::ConfiguredPlugin;
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4use std::str::FromStr;
5
6#[derive(Debug, Clone, Default, Serialize, Deserialize)]
7pub struct Route {
8    /// 名称
9    pub name: String,
10    /// Host,可选,* 代表不限制。
11    /// 支持泛域名,格式为 *.example.com,通配符只能出现在域名开头,需要在控制台校验。
12    pub host: String,
13    /// 路径,支持通配符,必须以"/"开头,全局唯一。
14    /// 同一域名下的路径不能存在冲突,如/api/*和/api/**就是冲突的路径,在控制台保存时需要校验。
15    /// 所有为 * 的域名下的路径也不能冲突。
16    pub path: String,
17    /// 转换后的匹配路径。
18    /// 由于路径匹配组件使用的是`matchit`,格式为`/xxx/{*any}`,
19    /// 它不符合常用的`/api/**`的格式,而`path`储存的是常用格式,
20    /// 所以这里需要做一次转换。
21    pub match_path: String,
22    /// 需要路由到的服务ID
23    pub service: String,
24    /// 请求方法:get | post | put | delete | patch | options
25    /// 支持配置多个。
26    /// 不参与路由唯一性验证。
27    pub methods: Vec<String>,
28    /// header匹配条件
29    /// 不参与路由唯一性验证。
30    #[serde(alias = "header_condition", alias = "header-condition")]
31    pub header: BTreeMap<String, String>,
32    /// query匹配条件
33    /// 不参与路由唯一性验证。
34    #[serde(alias = "query_condition", alias = "query-condition")]
35    pub query: BTreeMap<String, String>,
36    /// 前置过滤器插件,在请求阶段执行,多个按顺序串联执行
37    #[serde(default = "Vec::default", alias = "pre_filters", alias = "pre-filters")]
38    pub pre_filters: Vec<ConfiguredPlugin>,
39    /// 后置过滤器插件,在响应阶段执行,多个按顺序串联执行
40    #[serde(
41        default = "Vec::default",
42        alias = "post_filters",
43        alias = "post-filters"
44    )]
45    pub post_filters: Vec<ConfiguredPlugin>,
46    /// 是否开启鉴权
47    ///
48    /// 备注:网关本身只支持API Key鉴权即可,如果需要其他类型的鉴权方式,可将此处鉴权关闭,然后通过插件实现。
49    /// 考虑提供一些内置的鉴权插件。
50    #[serde(default = "bool::default", alias = "is_auth", alias = "is-auth")]
51    pub is_auth: bool,
52    /// 鉴权路径白名单
53    pub auth_white_list: Vec<String>,
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct RewriteRule {
58    /// 匹配模式(正则表达式)
59    pub pattern: String,
60    /// 替换字符串
61    pub replacement: String,
62}
63impl Route {
64    pub fn get_service(&self) -> &String {
65        &self.service
66    }
67
68    /// 构建请求路径
69    ///
70    /// - path 原始的请求路径
71    ///
72    /// 能执行到这里,说明已经匹配到该路由了。
73    /// (废弃,由插件实现)根据`strip_prefix`决定是否移除前缀
74    pub fn build_path(&self, path: &str) -> String {
75        /*let rewritten_path = self.apply_path_rewrite(path);*/
76        path.to_string()
77    }
78
79    /*pub fn apply_path_rewrite(&self, path: &str) -> String {
80        if let Some(rules) = &self.rewrite_rules {
81            let mut result = path.to_string();
82            for rule in rules {
83                if let Ok(regex) = regex::Regex::new(&rule.pattern) {
84                    result = regex.replace_all(&result, &rule.replacement).to_string();
85                }
86            }
87            result
88        } else {
89            path.to_string()
90        }
91    }*/
92}