Advertisement
SpiderLordCoder1st

Untitled

Jun 8th, 2025
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1.  
  2. async fn serve_html_with_replacement(
  3. file: &str,
  4. state: &AppState,
  5. ) -> Result<Response<Body>, StatusCode> {
  6. let path = Path::new("src/svelte/dist").join(file);
  7.  
  8. if path.extension().and_then(|e| e.to_str()) == Some("html") {
  9. let html = tokio_fs::read_to_string(&path)
  10. .await
  11. .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
  12. let replaced = html.replace("[[SITE_URL]]", &state.base_path);
  13. return Ok(Html(replaced).into_response());
  14. }
  15.  
  16. let bytes = tokio_fs::read(&path)
  17. .await
  18. .map_err(|_| StatusCode::NOT_FOUND)?;
  19. let content_type = from_path(&path).first_or_octet_stream().to_string();
  20.  
  21. Ok(Response::builder()
  22. .header("Content-Type", content_type)
  23. .body(Body::from(bytes))
  24. .unwrap())
  25. }
  26.  
  27. async fn handle_static_request(
  28. Extension(state): Extension<Arc<AppState>>,
  29. req: Request<Body>,
  30. ) -> Result<Response<Body>, StatusCode> {
  31.  
  32. let path = req.uri().path();
  33.  
  34. let file = if path == "/" || path.is_empty() {
  35. "index.html"
  36. } else {
  37. &path[1..]
  38. };
  39.  
  40. match serve_html_with_replacement(file, &state).await {
  41. Ok(res) => Ok(res),
  42. Err(status) => Ok(Response::builder()
  43. .status(status)
  44. .header("content-type", "text/plain")
  45. .body(format!("Error serving `{}`", file).into())
  46. .unwrap()),
  47. }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement