【Rust】フレームワーク自作: 静的ファイルハンドリング

静的ファイルはstaticに置くルールとする

    if path.starts_with("/static/") {
        let file_path = format!(".{}", path);

        match fs::read(&file_path) {
            Ok(contents) => {
                let content_type = get_content_type(path);
                let response = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: {}\r\nContent-Length: {}\r\n\r\n",
                    content_type,
                    contents.len()
                );
                let _ = stream.write_all(response.as_bytes());
                let _ = stream.write_all(&contents);
            }
            Err(_) => {
                let response = http_response(404, "text/plain", "Static file not found");
                let _ = stream.write_all(response.as_bytes());
            }
        }
        stream.flush().unwrap();
        return;
    }
// 

fn get_content_type(path: &str) -> &'static str {
    if path.ends_with(".css") {
        "text/css"
    } else if path.ends_with(".js") {
        "application/javascript"
    } else if path.ends_with(".png") {
        "image/png"
    } else if path.ends_with(".jpg") || path.ends_with(".jpeg") {
        "image/jpeg"
    } else if path.ends_with(".svg") {
        "image/svg+xml"
    } else if path.ends_with(".woff2") {
        "font/woff2"
    } else {
        "application/octet-stream"
    }
}

templatesフォルダのファイルが、以下対応できるようになります。

<link rel="stylesheet" href="/static/styles.css">
<script src="/static/app.js"></script>
<h1>Welcome to the Rust server!</h1>
<p>hello, {{ name }}</p>