Skip to content

Commit

Permalink
修复RewritePath无法使用绑定变量的BUG (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
w-sodalite authored Jan 20, 2024
1 parent decc228 commit 5d3eb4b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
6 changes: 4 additions & 2 deletions docs/layers/rewrite_path.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
|:-----|:-------:|:----:|:---:|:------|
| path | `[str]` | `Y` | | 重写的路径 |

备注:使用`{{variable}}`来使用[`Matcher - Path`]中绑定的变量。

## 配置示例

- ### 简单模式
Expand All @@ -19,7 +21,7 @@
matchers:
- Path=/a/:x+
layers:
- RewritePath=/b/{x}
- RewritePath=/b/{{x}}
service: Static=examples/resources
```
Expand All @@ -34,6 +36,6 @@
layers:
- kind: RewritePath
args:
path: /b/{x}
path: /b/{{x}}
service: Static=examples/resources
```
7 changes: 7 additions & 0 deletions examples/static.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ server:
router:
# 路由表
routes:
- id: backend
matchers:
- Path=/backend/:path+
layers:
- RewritePath=/{{path}}
service: Proxy=http://127.0.0.1:3000

# 静态文件
- id: static
service: Static=examples/resources
21 changes: 18 additions & 3 deletions satex-layer/src/make/rewrite_path/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use aho_corasick::AhoCorasick;
use hyper::{Request, Uri};
use tower::Service;
use tracing::debug;

pub use make::MakeRewritePathLayer;
use satex_core::essential::PathVariables;
use satex_core::essential::{Essential, PathVariables};

mod layer;
mod make;
Expand All @@ -20,6 +21,16 @@ impl<S> RewritePath<S> {
}
}

fn make_variable_template(key: &str) -> String {
let mut variable = String::with_capacity(key.len() + 4);
variable.push('{');
variable.push('{');
variable.push_str(key);
variable.push('}');
variable.push('}');
variable
}

impl<S, ReqBody> Service<Request<ReqBody>> for RewritePath<S>
where
S: Service<Request<ReqBody>>,
Expand All @@ -38,20 +49,24 @@ where
}

fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
let variables = req.extensions().get::<PathVariables>();
let variables = req
.extensions()
.get::<Essential>()
.and_then(|essential| essential.extensions.get::<PathVariables>());
let path = match variables {
None => self.path.clone(),
Some(variables) => {
let keys = variables
.0
.keys()
.map(|key| format!("{{{}}}", key))
.map(|key| make_variable_template(key))
.collect::<Vec<_>>();
let values = variables.0.values().collect::<Vec<_>>();
let corasick = AhoCorasick::new(keys).expect("Invalid path variable!");
corasick.replace_all(&self.path, values.as_slice())
}
};
debug!("Rewrite path: {} => {}", req.uri().path(), path);
let uri = req.uri();
let mut builder = Uri::builder();
if let Some(schema) = uri.scheme_str() {
Expand Down

0 comments on commit 5d3eb4b

Please sign in to comment.