Skip to content

Commit

Permalink
Add examples for ServeDir (#160)
Browse files Browse the repository at this point in the history
Fixes #149
  • Loading branch information
davidpdrsn committed Nov 13, 2021
1 parent 126b28a commit 5a09974
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
2 changes: 1 addition & 1 deletion tower-http/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ futures = "0.3"
hyper = { version = "0.14", features = ["full"] }
once_cell = "1"
tokio = { version = "1", features = ["full"] }
tower = { version = "0.4.6", features = ["buffer", "util", "retry", "make"] }
tower = { version = "0.4.10", features = ["buffer", "util", "retry", "make"] }
tracing-subscriber = "0.2"

[features]
Expand Down
58 changes: 58 additions & 0 deletions tower-http/src/services/fs/serve_dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,64 @@ use tower_service::Service;
/// - Any segment of the path contains `..`
/// - Any segment of the path contains a backslash
/// - We don't have necessary permissions to read the file
///
/// # Example
///
/// ```
/// use tower_http::services::ServeDir;
///
/// // This will serve files in the "assets" directory and
/// // its subdirectories
/// let service = ServeDir::new("assets");
///
/// # async {
/// // Run our service using `hyper`
/// let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));
/// hyper::Server::bind(&addr)
/// .serve(tower::make::Shared::new(service))
/// .await
/// .expect("server error");
/// # };
/// ```
///
/// # Handling files not found
///
/// By default `ServeDir` will return an empty `404 Not Found` response if there
/// is no file at the requested path. That can be customized by using
/// [`and_then`](tower::ServiceBuilder::and_then) to change the response:
///
/// ```
/// use tower_http::services::fs::{ServeDir, ServeDirResponseBody};
/// use tower::ServiceBuilder;
/// use http::{StatusCode, Response};
/// use http_body::{Body as _, Full};
/// use std::io;
///
/// let service = ServiceBuilder::new()
/// .and_then(|response: Response<ServeDirResponseBody>| async move {
/// let response = if response.status() == StatusCode::NOT_FOUND {
/// let body = Full::from("Not Found")
/// .map_err(|err| match err {})
/// .boxed();
/// Response::builder()
/// .status(StatusCode::NOT_FOUND)
/// .body(body)
/// .unwrap()
/// } else {
/// response.map(|body| body.boxed())
/// };
///
/// Ok::<_, io::Error>(response)
/// })
/// .service(ServeDir::new("assets"));
/// # async {
/// # let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));
/// # hyper::Server::bind(&addr)
/// # .serve(tower::make::Shared::new(service))
/// # .await
/// # .expect("server error");
/// # };
/// ```
#[derive(Clone, Debug)]
pub struct ServeDir {
base: PathBuf,
Expand Down

0 comments on commit 5a09974

Please sign in to comment.