Skip to content

Commit

Permalink
feature: add tower-http support
Browse files Browse the repository at this point in the history
  • Loading branch information
skymacro111666 committed May 30, 2024
1 parent df0b815 commit 593617d
Show file tree
Hide file tree
Showing 4 changed files with 214 additions and 4 deletions.
180 changes: 179 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ tokio = { version = "1.37.0", features = [
"tokio-macros",
] }
toml = "0.8.12"
tower-http = { version = "0.5.2", features = [
"compression-full",
"cors",
"fs",
"trace",
] }
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
zxcvbn = "2.2.2"
24 changes: 22 additions & 2 deletions src/process/http_serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;

use tower_http::services::ServeDir;
use tracing::{info, warn};

#[derive(Debug)]
Expand All @@ -16,8 +17,12 @@ struct HttpServerState {
pub async fn process_http_serve(path: PathBuf, port: u16) -> Result<()> {
let addr = SocketAddr::from(([0, 0, 0, 0], port));
info!("Serving {:?} on {}", path, addr);
let state = HttpServerState { path };
let router = Router::new().route("/*path", get(file_handler).with_state(Arc::new(state)));
let state = HttpServerState { path: path.clone() };
let dir_service = ServeDir::new(path);
let router = Router::new()
.route("/*path", get(file_handler))
.nest_service("/tower", dir_service)
.with_state(Arc::new(state));
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, router).await?;
Ok(())
Expand Down Expand Up @@ -49,3 +54,18 @@ async fn file_handler(
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[tokio::test]
async fn test_file_handler() {
let state = Arc::new(HttpServerState {
path: PathBuf::from("."),
});
let (status, content) = file_handler(State(state), Path("Cargo.toml".to_string())).await;
assert_eq!(status, StatusCode::OK);
assert!(content.trim().starts_with("[package]"));
}
}
8 changes: 7 additions & 1 deletion test.http
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
### Test index page

GET http://localhost:8080/aaa
GET http://localhost:8080/fixtures/blake3.txt
Range: bytes=0-100

### Test static file with tower-http

GET http://localhost:8080/tower/fixtures/ed25519.pk
Range: bytes=0-6

0 comments on commit 593617d

Please sign in to comment.