1c7e7481f6
Issue: Previous edit missed L11 hardcoded path
Solution: Use same env var + current_exe() pattern as L24
Verification: strings shows 0 dev paths in binary
D-4: ✅ Complete
68 lines
2.4 KiB
Rust
68 lines
2.4 KiB
Rust
use axum::{extract::Path, http::StatusCode, routing::get, Router};
|
|
|
|
use super::types::AppState;
|
|
|
|
async fn doc_redirect() -> axum::response::Redirect {
|
|
axum::response::Redirect::to("/doc-wasm")
|
|
}
|
|
|
|
async fn wasm_doc_handler() -> Result<impl axum::response::IntoResponse, (StatusCode, &'static str)>
|
|
{
|
|
let base_str = std::env::var("MOMENTRY_DOCS_DIR")
|
|
.unwrap_or_else(|_| {
|
|
std::env::current_exe()
|
|
.ok()
|
|
.and_then(|p| p.parent().map(|d| d.join("docs_v1.0/doc_wasm").to_string_lossy().to_string()))
|
|
.unwrap_or_else(|| "docs_v1.0/doc_wasm".to_string())
|
|
});
|
|
let path = std::path::Path::new(&base_str).join("index.html");
|
|
match tokio::fs::read_to_string(path).await {
|
|
Ok(html) => Ok(([("content-type", "text/html; charset=utf-8")], html)),
|
|
Err(_) => Err((StatusCode::NOT_FOUND, "Doc not found")),
|
|
}
|
|
}
|
|
|
|
async fn wasm_doc_file_handler(
|
|
Path(file): Path<String>,
|
|
) -> Result<impl axum::response::IntoResponse, (StatusCode, &'static str)> {
|
|
if file.contains("..") || file.contains("//") {
|
|
return Err((StatusCode::NOT_FOUND, "Invalid path"));
|
|
}
|
|
let base_str = std::env::var("MOMENTRY_DOCS_DIR")
|
|
.unwrap_or_else(|_| {
|
|
std::env::current_exe()
|
|
.ok()
|
|
.and_then(|p| p.parent().map(|d| d.join("docs_v1.0/doc_wasm").to_string_lossy().to_string()))
|
|
.unwrap_or_else(|| "docs_v1.0/doc_wasm".to_string())
|
|
});
|
|
let base = std::path::Path::new(&base_str);
|
|
let path = base.join(&file);
|
|
if !path.exists() || !path.starts_with(base) {
|
|
return Err((StatusCode::NOT_FOUND, "File not found"));
|
|
}
|
|
let data = tokio::fs::read(&path)
|
|
.await
|
|
.map_err(|_| (StatusCode::NOT_FOUND, "Read error"))?;
|
|
let mime = if file.ends_with(".wasm") {
|
|
"application/wasm"
|
|
} else if file.ends_with(".js") {
|
|
"application/javascript"
|
|
} else if file.ends_with(".md") {
|
|
"text/markdown; charset=utf-8"
|
|
} else if file.ends_with(".css") {
|
|
"text/css"
|
|
} else {
|
|
"application/octet-stream"
|
|
};
|
|
Ok(([("content-type", mime)], data))
|
|
}
|
|
|
|
pub fn doc_routes() -> Router<AppState> {
|
|
Router::new()
|
|
.route("/doc", get(doc_redirect))
|
|
.route("/doc/*file", get(doc_redirect))
|
|
.route("/dev-doc", get(doc_redirect))
|
|
.route("/doc-wasm", get(wasm_doc_handler))
|
|
.route("/doc-wasm/*file", get(wasm_doc_file_handler))
|
|
}
|