Generating Controllers
The fastest way to create a new controller is using the Kit CLI:- Create
src/controllers/user.rswith a controller stub - Update
src/controllers/mod.rsto export the new controller
Controller Structure
Controllers are async functions that take aRequest and return a Response:
The Handler Signature
Every controller handler follows this pattern:async fn: Controllers are asynchronous, allowing non-blocking I/O operationsRequest: Contains all information about the incoming HTTP requestResponse: An alias forResult<HttpResponse, HttpResponse>, enabling the?operator
The Request Object
TheRequest struct provides Laravel-like access to request data:
Getting Route Parameters
Access dynamic URL segments defined in your routes:Getting Headers
Access HTTP headers from the request:Request Methods
| Method | Return Type | Description |
|---|---|---|
method() | &Method | HTTP method (GET, POST, etc.) |
path() | &str | Request path (e.g., /users/123) |
param(name) | Result<&str, ParamError> | Get a route parameter |
params() | &HashMap<String, String> | Get all route parameters |
header(name) | Option<&str> | Get a header value |
is_inertia() | bool | Check if Inertia.js request |
inertia_version() | Option<&str> | Get Inertia version |
Creating Responses
Controllers return responses using helper methods and macros:JSON Responses
Text Responses
Setting Status Codes
For more response options, see the Responses documentation.
RESTful Controllers
Kit encourages organizing controllers following REST conventions:Error Handling in Controllers
Use the? operator for clean error propagation:
For more error handling options, see the Responses documentation.
Dependency Injection
UseApp::resolve() to inject dependencies from the container:
File Organization
The standard file structure for controllers:Practical Examples
API Controller with Validation
Controller with Redirects
Summary
| Feature | Usage |
|---|---|
| Generate controller | kit make:controller Name |
| Handler signature | pub async fn name(req: Request) -> Response |
| Get route param | req.param("id")? |
| Get all params | req.params() |
| Get header | req.header("Authorization") |
| Get HTTP method | req.method() |
| Get path | req.path() |
| JSON response | json_response!({...}) |
| Text response | text_response!("...") |
| Set status | .status(201) |
| Redirect | redirect!("route.name").into() |