Skip to main content

Basic Routes

Mapping HTTP requests to handlers

Actix 4.9+ 5 min read

# Basic Routes

In Actix Web, routing is the mechanism that maps incoming HTTP requests to specific handler functions. The framework provides a simple yet powerful pattern-matching language to ensure that the correct block of code executes when a user accesses a particular URL.

#Why Routing Matters

Without routing, your application wouldn't know how to differentiate a request for the homepage from a request to submit a form. Routing serves as the entry point to your application's logic.

#Defining Routes

Actix Web provides several ways to define routes. The most straightforward approach uses the route macro, but you can also define routes manually using web::route().

code_blocksrust
use actix_web::{get, web, App, HttpServer, Responder};

#[get("/")]
async fn index() -> impl Responder {
    "Hello, World!"
}

async fn manual_route() -> impl Responder {
    "This is a manually configured route."
}

You can register these routes when initializing the App in your HttpServer::new closure. It's considered a best practice to keep your handler logic separated from the routing configuration, especially in larger applications.

#Trailing Slashes

By default, Actix Web handles trailing slashes strictly. A request to /about will not match a route defined as /about/. You can use middleware to normalize paths if you prefer a more lenient approach.

Was this page helpful?

Reference Implementation

The following code snippet demonstrates the authoritative pattern for this documentation.

src/main.rs
1use actix_web::{get, web, App, HttpServer, Responder};
2
3#[get("/hello")]
4async fn hello() -> impl Responder {
5 "Hello from Actix Web!"
6}
7
8async fn about() -> impl Responder {
9 "About page"
10}
11
12#[actix_web::main]
13async fn main() -> std::io::Result<()> {
14 HttpServer::new(|| {
15 App::new()
16 .service(hello)
17 .route("/about", web::get().to(about))
18 })
19 .bind(("127.0.0.1", 8080))?
20 .run()
21 .await
22}
23
Was this page helpful?