#tower-service #static-file #serve-static

tower-serve-static

Tower service that serves static files

2 releases

0.1.1 Jan 25, 2024
0.1.0 Jan 5, 2024

#24 in #tower-service

Download history 749/week @ 2024-07-21 198/week @ 2024-07-28 494/week @ 2024-08-04 268/week @ 2024-08-11 182/week @ 2024-08-18 154/week @ 2024-08-25 140/week @ 2024-09-01 240/week @ 2024-09-08 162/week @ 2024-09-15 194/week @ 2024-09-22 245/week @ 2024-09-29 282/week @ 2024-10-06 336/week @ 2024-10-13 425/week @ 2024-10-20 486/week @ 2024-10-27 381/week @ 2024-11-03

1,644 downloads per month
Used in saasbase

MIT license

33KB
630 lines

Tower Serve Static

crates.io docs.rs Build Status dependency status codecov Lines Of Code

Tower file services using include_dir and include_bytes to embed assets into the binary.

Usage

Cargo.toml

tower-serve-static = { git = "https://github.com/jannik4/tower-serve-static", version = "0.1.0" }
include_dir = "0.7.0"

Serve Static File

use tower_serve_static::{ServeFile, include_file};

// File is located relative to `CARGO_MANIFEST_DIR` (the directory containing the manifest of your package).
// This will embed and serve the `README.md` file.
let service = ServeFile::new(include_file!("/README.md"));

// Run our service using `axum`
let app = axum::Router::new().nest_service("/", service);

// run our app with axum, listening locally on port 3000
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
axum::serve(listener, app).await?;

Serve Static Directory

use tower_serve_static::{ServeDir};
use include_dir::{Dir, include_dir};

// Use `$CARGO_MANIFEST_DIR` to make path relative to your package.
// This will embed and serve files in the `src` directory and its subdirectories.
static ASSETS_DIR: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/src");
let service = ServeDir::new(&ASSETS_DIR);

// Run our service using `axum`
let app = axum::Router::new().nest_service("/", service);

// run our app with axum, listening locally on port 3000
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
axum::serve(listener, app).await?;

Credits

The implementation is based on the tower-http file services (more specifically version 0.1.2) and adapted to use include_dir/include_bytes instead of the filesystem at runtime.

Dependencies

~4–10MB
~99K SLoC