capy-framework 0.3.0

An opinionated full-stack Rust web framework with strong conventions and sensible defaults.
Documentation
use crate::{AppError, Result};
use axum::{
    body::Body,
    extract::Request,
    http::{Method, StatusCode},
    response::{IntoResponse, Response},
};
use std::path::{Path, PathBuf};
use tower::ServiceExt;
use tower_http::services::{ServeDir, ServeFile};

pub(crate) fn validate(directory: &Path) -> Result<()> {
    if !directory.join("index.html").is_file()
        || std::fs::File::open(directory.join("index.html")).is_err()
    {
        return Err(AppError::Configuration(format!(
            "Capy could not find the frontend build at {}.\n\nRun:\n\n    capy build\n\nDeploy frontend/dist alongside the binary and run from the application root.",
            directory.display()
        )));
    }
    Ok(())
}

pub(crate) async fn serve(directory: PathBuf, request: Request) -> Response {
    let path = request.uri().path();
    // This guard also reserves /api when no API routes are registered. A missing
    // endpoint must never turn into a successful HTML response.
    if path == "/api" || path.starts_with("/api/") {
        return AppError::NotFound.into_response();
    }
    if request.method() != Method::GET && request.method() != Method::HEAD {
        return AppError::MethodNotAllowed.into_response();
    }
    // Asset typos should return 404, rather than index.html with a wrong MIME type.
    let browser_route = !path.starts_with("/assets/")
        && !path.rsplit('/').next().unwrap_or("").contains('.')
        && !path.split('/').any(|segment| segment.starts_with('.'));
    let (parts, _) = request.into_parts();
    let response = ServeDir::new(&directory)
        .append_index_html_on_directories(false)
        .oneshot(Request::from_parts(parts.clone(), Body::empty()))
        .await
        .unwrap_or_else(|never| match never {})
        .into_response();
    if response.status() != StatusCode::NOT_FOUND || !browser_route {
        return response;
    }
    ServeFile::new(directory.join("index.html"))
        .oneshot(Request::from_parts(parts, Body::empty()))
        .await
        .unwrap_or_else(|never| match never {})
        .into_response()
}