Handler
- Dart course
- Advanced
- Lesson 26/83
- 5 min
Learn request handling with a shelf Handler.
The Handler type
shelf defines a handler as typedef Handler = FutureOr<Response> Function(Request). So a handler can be synchronous (Response) or asynchronous (Future<Response>).
A synchronous handler suits simple work: Response okHandler(Request r) => Response.ok('ok');.
An asynchronous handler is needed for I/O: Future<Response> dbHandler(Request r) async { var data = await fetch(); return Response.ok(data); }.
Reading from a Request
A handler reads request info via the Request parameter: req.method (GET, POST...), req.requestedUri.path, req.headers.
Reading the body is asynchronous: var body = await req.readAsString();. This is used to parse JSON or form data.
Example: Response echoHandler(Request r) => Response.ok('path: ${r.requestedUri.path}');. Writes the request path into the response.
Practice Echo the request path
Add import 'package:shelf/shelf.dart';. Define Response echoHandler(Request r) => Response.ok('yol: ${r.requestedUri.path}');. In main add var resp = echoHandler(Request('GET', Uri.parse('http://localhost/merhaba'))); and print(await resp.readAsString()); (make main async).
Starter code
void main() {
// add shelf import; define echoHandler
// call the handler with /merhaba; read body async and print
}Sample solution
import 'package:shelf/shelf.dart';
Response echoHandler(Request r) => Response.ok('yol: ${r.requestedUri.path}');
void main() async {
var resp = echoHandler(Request('GET', Uri.parse('http://localhost/merhaba')));
print(await resp.readAsString());
}Expected output
yol: /merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Async handler return type
Future<____> dbHandler(Request r) async { ... }
Future<Response> dbHandler(Request r) async { ... }
Explanation: an async handler returns Future<Response>.
2 Can a handler be synchronous?
- No, always async
- Yes, it can return Response Correct answer
- Only Future<Response>
- Only Stream<Response>
Explanation: a handler can return a synchronous Response (thanks to FutureOr).
3 Match the Request parts
| Term | Meaning |
|---|---|
req.method |
GET/POST |
req.requestedUri |
URL |
req.headers |
Headers |
req.readAsString |
Body |