A router is a core component of H4. It's used to route requests to the appropriate handler.
Create a router instance with optional base path:
// Default router with no base path
final router = createRouter ();
// Router with base path
final apiRouter = createRouter (basePath : '/api' );
You can create multiple routers with different base paths and combine them:
void main () {
final app = createApp ();
final v1Router = createRouter (basePath : '/v1' );
final v2Router = createRouter (basePath : '/v2' );
app. use (v1Router);
app. use (v2Router);
v1Router. get ( "/users" , (event) => getUserList ());
v2Router. get ( "/users" , (event) => getUserListV2 ());
}
This allows you to organize routes better in some cases. E.g adding versioning to your app with
routes prefixed with v1, v2, etc.
Handle all HTTP methods with explicit handlers:
router. get ( "/resource" , (event) => "GET handler" );
router. post ( "/resource" , (event) => "POST handler" );
router. put ( "/resource" , (event) => "PUT handler" );
router. delete ( "/resource" , (event) => "DELETE handler" );
router. patch ( "/resource" , (event) => "PATCH handler" );
router. head ( "/resource" , (event) => "HEAD handler" );
router. options ( "/resource" , (event) => "OPTIONS handler" );
router. trace ( "/resource" , (event) => "TRACE handler" );
router. all ( "/resource" , (event) => "Handles ALL method types" );
Capture dynamic path segments using colon syntax:
router. get ( "/users/:id" , (event) {
final userId = getRouteParam (event, 'id' );
return { 'user' : fetchUser (userId)};
});
router. get ( "/posts/:slug/comments/:commentId" , (event) {
final slug = getRouteParam (event, 'slug' );
final commentId = getRouteParam (event, 'commentId' );
return fetchComment (slug, commentId);
});
Handle unmatched routes with wildcard pattern:
// Match all requests under /api
router. all ( "/api/*" , handle404);
// Global 404 handler example
router. all ( "**" , (event) {
event.statusCode = 404 ;
return "Route not found" ;
});
Return various response types directly:
router. get ( "/text" , (event) => "Plain text response" );
router. get ( "/json" , (event) => { "key" : "value" });
router. get ( "/html" , (event) => "<h1>Hello</h1>" );
router. get ( "/bytes" , (event) => [ 1 , 2 , 3 ]);