首页 > 解决方案 > 如何使用一个主路由创建多个 html 页面?

问题描述

我正在尝试创建一个网站,该网站具有多个社区供稿,例如一个用于保龄球,另一个用于扑克,如下所示:localhost:8088/communities/bowling & localhost:8088/communities/poker。

我使用 actix 作为在 Rust 编程语言下运行的网络服务器。

有没有一种方法可以让在 localhost:8088/communities 下运行的所有地址都遇到相同的 Web 文件,这样我就可以只有一个主路由?

然后存储像 /bowling 或 /poker 这样的附加标头,以便我可以向服务器提交单独的请求以获取相关的帖子提要?也许我可以在调用网页时将附加标题信息保存在 javascript 变量中?- 就像我去 /poker 时一样,名为 communityType 的变量被设置为 poker。我该怎么做这样的事情?

因为没有人可以为大约 100 多个不同的社区中的每一个制作 HTML 页面。

我在这里先向您的帮助表示感谢!

标签: javascriptrustheaderrust-actix

解决方案


我对这个板条箱不是很熟悉,但是根据文档,您可以使用它#[get("/route/this/function/will/support")]来定义如何处理路由。假设我写的正确,这应该会以小消息响应,告诉您使用时您在哪个社区路线上。

use actix_web::{get, web, App, HttpServer, Responder};

#[get("/communities/{name}")]
async fn communities_route(web::Path(name): web::Path<String>) -> impl Responder {
    format!("This is the page for the {:} community!", name)
}

您还可以将其扩展为具有发言权#[get("/communities/{name}/forums")]#[get("/communities/{name}/{file}")]处理所有社区在每个社区基础上拥有的公共路线。

编辑:

听起来您在初始化to use时还需要包含.service(communities_route)在 main 函数中。如果您直接配置服务,您还可以更好地控制路由的处理方式。App#[get(x)]

这是他们的hello world 示例中的一个片段。只要您访问除"/index.html".

async fn index(req: HttpRequest) -> &'static str {
    println!("REQ: {:?}", req);
    "Hello world!"
}

App::new()
.service(web::resource("/index.html").to(|| async { "Hello world!" }))
.service(web::resource("/").to(index))

我建议在 github 上查看他们的示例。看起来他们为许多不同的用例提供了一堆简洁的示例。


推荐阅读