Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

希望增加个named函数 #879

Open
dulumao opened this issue Aug 20, 2024 · 2 comments
Open

希望增加个named函数 #879

dulumao opened this issue Aug 20, 2024 · 2 comments

Comments

@dulumao
Copy link

dulumao commented Aug 20, 2024

可以给router加个named函数嘛,类似
Router::new().path("edit/id:num").post(edit).named("user_edit")

这样,在后续的handler中可以获取到,并且做uri赋值的时候,方便生成uri

@dulumao dulumao changed the title 希望增加哥named函数 希望增加个named函数 Aug 20, 2024
@chrislearn
Copy link
Member

Salvo 中的 Router 本身是嵌套的,路径只是 Router 中的一个 Filter,所以,是给 Router 命名还是给 Router 中的路径命名?如果Router 不包含 Path 的 Filter 呢?如果多个 Router 存在相同的路径,是都起同样的名字? 会不会很怪异?会不会路径不同又有相同名字?如何检测冲突?

感觉不好实现,也没太大的意义。

@dulumao
Copy link
Author

dulumao commented Aug 21, 2024

很有意义的,对于微服务还好,路由少,如果是一个相对复杂的项目,比如一个电商吧,涉及的路由就很多了,后端经常需要生成url,返还给前端,这个时候,去拼凑uri就很麻烦了, 很多类似的框架都有这种功能,其实有个简单的办法,就是PathFilter里的字段给pub,或者将PathParser给设置成pub,这样就可以重新parse,类似:
let filter = PathFilter::new("/api/v1/test/handle_filter_path/guid:my_custom_guid/edit")
因为PathFilter内部自己调用了PathParser,也就无法进行进一步的获取计算了,代码被写死了,
这样,可以自己扩充request trait的方法,增加一个uri拼凑路由,这样就不需要router name了
比如重写一个

#[handler]
// https://0.0.0.0/edit/<user_id>/<article_id>?ref=test_user&ref_code=abc123
async fn handle_edit(req: &mut Request, res: &mut Response) {
    // before url https://0.0.0.0/edit/10/5?ref=test_user&ref_code=abc123
    let params = HashMap::from([("user_id", "1"), ("article_id","100")]);
    let queries = HashMap::from([("ref", "admin"), ("ref_code","11111111")]);
    let url = req.make_uri(req, params, queries);
    // or let url = req.make_uri(“/edit/<user_id>/<article_id>”, params, queries);
    // after url = https://0.0.0.0/edit/1/100?ref=admin&ref_code=11111111

    res.render(Text::Json(
        json!({
            "code": 200,
            "success": true,
            "payload": {
                "redirect_url": url
            }
        })
        .to_string(),
    ))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants