(req: tiny_http::Request, dir: &Path, url: &str)
| 33 | } |
| 34 | |
| 35 | fn serve_file(req: tiny_http::Request, dir: &Path, url: &str) { |
| 36 | let rel = url.trim_start_matches('/'); |
| 37 | let mut path = dir.join(rel); |
| 38 | if rel.is_empty() || path.is_dir() { |
| 39 | path = path.join("index.html"); |
| 40 | } |
| 41 | match std::fs::read(&path) { |
| 42 | Ok(bytes) => { |
| 43 | let ct = content_type(&path); |
| 44 | let resp = if ct == "text/html" { |
| 45 | let html = inject_livereload(&String::from_utf8_lossy(&bytes)); |
| 46 | Response::from_string(html).with_header(header("Content-Type", ct)) |
| 47 | } else { |
| 48 | Response::from_data(bytes).with_header(header("Content-Type", ct)) |
| 49 | }; |
| 50 | let _ = req.respond(resp); |
| 51 | } |
| 52 | Err(_) => { |
| 53 | let _ = req.respond(Response::from_string("404 not found").with_status_code(404)); |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | fn content_type(path: &Path) -> &'static str { |
| 59 | match path.extension().and_then(|e| e.to_str()) { |
no test coverage detected