Trailing Slash

A middleware for automatically adding or removing trailing /.

Use Cases

The Trailing Slash middleware is particularly useful in the following scenarios:

  • URL Normalization: Ensures all URLs follow a consistent format (by uniformly adding or removing trailing slashes), which helps improve SEO and avoid duplicate content issues.

  • Simplified Route Handling: Eliminates the need to write separate routing logic for URLs with and without trailing slashes, as the middleware automatically handles this conversion.

  • Compatibility: Some clients may automatically add or remove trailing slashes from URLs. This middleware ensures that requests are correctly routed.

  • Redirect Management: Can be configured to automatically redirect URLs with trailing slashes to those without (or vice versa), enhancing the user experience.

  • Avoiding Route Conflicts: In many web frameworks, /path and /path/ may be treated as different routes. This middleware can handle them uniformly.

Example Code

main.rs
Cargo.toml
use salvo::prelude::*;
use salvo::trailing_slash::add_slash;

#[handler]
async fn hello() -> &'static str {
    "Hello"
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt().init();
    let router = Router::with_hoop(add_slash())
        .push(Router::with_path("hello").get(hello))
        .push(Router::with_path("hello.world").get(hello));
    let acceptor = TcpListener::new("0.0.0.0:8698").bind().await;
    Server::new(acceptor).serve(router).await;
}