Rust如何编制前端路由

目的:根据前端build文件夹下的目录结构,生成路由,将前端html文件返回。

rust 复制代码
/// 设置 HTML 文件路由
pub fn route(cfg: &mut web::ServiceConfig) {
    if Path::new("client/build/index.html").exists() {
        let index_content = match fs::read_to_string("client/build/index.html") {
            Ok(content) => content,
            Err(e) => {
                log::error!("无法读取 index.html: {}", e);
                return;
            }
        };

        let index_content = web::Data::new(index_content);

        cfg.service(
            web::resource("/user/authorize/")
                .app_data(index_content.clone())
                .route(web::get().to(serve_index)),
        );

        cfg.service(
            web::resource(
                "/condition-monitoring/parameter-display/parameter-list-display/create-list",
            )
            .app_data(index_content.clone())
            .route(web::get().to(serve_index)),
        );

        for entry in WalkDir::new("client/build") {
            if let Ok(entry) = entry {
                if entry.path().extension().map_or(false, |ext| ext == "html") {
                    if let Ok(rel_path) = entry.path().strip_prefix("client/build") {
                        let route_path = rel_path
                            .with_extension("")
                            .to_string_lossy()
                            .replace("\\", "/");
                        let route_path = if route_path.ends_with("index") {
                            route_path.trim_end_matches("index").to_string()
                        } else {
                            route_path.to_string()
                        };

                        cfg.service(
                            web::resource(format!("/{}", route_path))
                                .app_data(index_content.clone())
                                .route(web::get().to(serve_index)),
                        );
                    }
                }
            }
        }
    } else {
        log::error!("index.html 未找到");
    }
}

在使用 svelte开发的时候遇到以下问题:

1、+layout.ts 设置 trailingSlash = 'always' 之后,无法索引到正确路径;

解决方案:trailingSlash = 'never'

2、要用客户端接管所有的路由处理

ts 复制代码
# svelte.config.js
		adapter: adapter({
			fallback: 'index.html',
		}),
相关推荐
pas1362 小时前
40-mini-vue 实现三种联合类型
前端·javascript·vue.js
摇滚侠3 小时前
2 小时快速入门 ES6 基础视频教程
前端·ecmascript·es6
珑墨3 小时前
【Turbo】使用介绍
前端
军军君014 小时前
Three.js基础功能学习十三:太阳系实例上
前端·javascript·vue.js·学习·3d·前端框架·three
打小就很皮...5 小时前
Tesseract.js OCR 中文识别
前端·react.js·ocr
wuhen_n5 小时前
JavaScript内存管理与执行上下文
前端·javascript
Hi_kenyon6 小时前
理解vue中的ref
前端·javascript·vue.js
大卫小东(Sheldon)6 小时前
GIM 2.0 发布:真正让 AI 提交消息可定制、可控、可项目级优化
git·rust·gim
落霞的思绪7 小时前
配置React和React-dom为CDN引入
前端·react.js·前端框架
Hacker_Z&Q7 小时前
CSS 笔记2 (属性)
前端·css·笔记