routes! macro. Routes map URLs to handler functions (controllers), support dynamic parameters, named routes for URL generation, and per-route middleware.
Defining Routes
Routes are defined insrc/routes.rs using the routes! macro. Each route specifies an HTTP method, a path, and a handler function:
routes! macro automatically generates a register() function that returns a configured Router.
HTTP Methods
Kit provides helper functions for all standard HTTP methods:| Method | Function | Usage |
|---|---|---|
| GET | get(path, handler) | Retrieve resources |
| POST | post(path, handler) | Create resources |
| PUT | put(path, handler) | Update resources |
| DELETE | delete(path, handler) | Delete resources |
Route Parameters
Dynamic segments in your URLs are defined using curly braces{param}. These parameters are extracted and made available to your handler through the request:
request.param():
Named Routes
Named routes allow you to generate URLs without hardcoding paths. Use.name() to assign a name to a route:
Naming Conventions
Follow Laravel-style naming conventions for consistency:| Route | Name |
|---|---|
GET /users | users.index |
GET /users/{id} | users.show |
POST /users | users.store |
PUT /users/{id} | users.update |
DELETE /users/{id} | users.destroy |
URL Generation
Generate URLs from named routes using theroute() function:
Route Middleware
Apply middleware to specific routes using.middleware():
For more details on creating middleware, see the Middleware documentation.
Route Groups
Group related routes that share a common prefix and/or middleware using the fluentRouter API:
Group Features
- Prefix: All routes in the group have the prefix prepended to their paths
- Middleware: Apply middleware to all routes in the group at once
- Chaining: Groups can be chained with other routes and groups
File Organization
The standard file structure for routing in a Kit application:Summary
| Feature | Syntax | Description |
|---|---|---|
| Define routes | routes! { ... } | Macro for clean route definitions |
| GET route | get(path, handler) | Handle GET requests |
| POST route | post(path, handler) | Handle POST requests |
| PUT route | put(path, handler) | Handle PUT requests |
| DELETE route | delete(path, handler) | Handle DELETE requests |
| Route parameter | /users/{id} | Dynamic URL segment |
| Access parameter | request.param("id") | Get parameter value |
| Named route | .name("users.show") | Name for URL generation |
| Generate URL | route("name", &[...]) | Generate URL from name |
| Route middleware | .middleware(M) | Apply middleware to route |
| Route group | .group("/prefix", |r| ...) | Group routes with prefix |