Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- async fn serve_html_with_replacement(
- file: &str,
- state: &AppState,
- ) -> Result<Response<Body>, StatusCode> {
- let path = Path::new("src/svelte/dist").join(file);
- if path.extension().and_then(|e| e.to_str()) == Some("html") {
- let html = tokio_fs::read_to_string(&path)
- .await
- .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
- let replaced = html.replace("[[SITE_URL]]", &state.base_path);
- return Ok(Html(replaced).into_response());
- }
- let bytes = tokio_fs::read(&path)
- .await
- .map_err(|_| StatusCode::NOT_FOUND)?;
- let content_type = from_path(&path).first_or_octet_stream().to_string();
- Ok(Response::builder()
- .header("Content-Type", content_type)
- .body(Body::from(bytes))
- .unwrap())
- }
- async fn handle_static_request(
- Extension(state): Extension<Arc<AppState>>,
- req: Request<Body>,
- ) -> Result<Response<Body>, StatusCode> {
- let path = req.uri().path();
- let file = if path == "/" || path.is_empty() {
- "index.html"
- } else {
- &path[1..]
- };
- match serve_html_with_replacement(file, &state).await {
- Ok(res) => Ok(res),
- Err(status) => Ok(Response::builder()
- .status(status)
- .header("content-type", "text/plain")
- .body(format!("Error serving `{}`", file).into())
- .unwrap()),
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement