Skip to content

Commit

Permalink
feat: add path normalization that removes any trailing slashes
Browse files Browse the repository at this point in the history
  • Loading branch information
koskeller committed Feb 19, 2024
1 parent 7ac4ab1 commit 01d02a3
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ tokio = { version = "1.36.0", features = ["full"] }
axum = "0.7.4"
hyper = "1.1.0"
tower = { version = "0.4.13", features = []}
tower-http = { version = "0.5.1", features = ["trace", "timeout", "request-id", "cors"] }
tower-http = { version = "0.5.1", features = ["trace", "timeout", "request-id", "cors", "normalize-path"] }

sqlx = { version = "0.7.3", features = ["postgres", "runtime-tokio-rustls", "macros", "migrate", "chrono", "json", "uuid"] }

Expand Down
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,13 @@ pub fn router(cfg: Config, db: Db) -> Router {
// Default value is 15 seconds.
let timeout_layer = middleware::timeout_layer();

// Any trailing slashes from request paths will be removed. For example, a request with `/foo/`
// will be changed to `/foo` before reaching the inner service.
let normalize_path_layer = middleware::normalize_path_layer();

Router::new()
.merge(routes::router())
.layer(normalize_path_layer)
.layer(cors_layer)
.layer(timeout_layer)
.layer(propagate_request_id_layer)
Expand Down
9 changes: 9 additions & 0 deletions src/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use axum::http::HeaderName;
use hyper::Request;
use tower_http::{
cors::{AllowHeaders, Any, CorsLayer},
normalize_path::NormalizePathLayer,
request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer},
timeout::TimeoutLayer,
};
Expand Down Expand Up @@ -50,3 +51,11 @@ pub fn cors_layer() -> CorsLayer {
pub fn timeout_layer() -> TimeoutLayer {
TimeoutLayer::new(Duration::from_secs(15))
}

/// Middleware that normalizes paths.
///
/// Any trailing slashes from request paths will be removed. For example, a request with `/foo/`
/// will be changed to `/foo` before reaching the inner service.
pub fn normalize_path_layer() -> NormalizePathLayer {
NormalizePathLayer::trim_trailing_slash()
}

0 comments on commit 01d02a3

Please sign in to comment.