RequestHandler class abstract
Defines the interface for handling HTTP requests.
This is the core abstraction that different server implementations will adapt to. When using the server_testing package, you need to implement this interface to handle requests from the testing client.
There are two main ways to implement this interface:
- Create a custom implementation for testing specific features
- Create an adapter for an existing web framework or application
Example Custom Implementation
class SimpleJsonHandler implements RequestHandler {
final Map<String, dynamic> _data;
SimpleJsonHandler(this._data);
@override
Future<void> handleRequest(HttpRequest request) async {
final response = request.response;
response.statusCode = 200;
response.headers.contentType = ContentType.json;
response.write(jsonEncode(_data));
await response.close();
}
@override
Future<int> startServer({int port = 0}) async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, port);
server.listen(handleRequest);
return server.port;
}
@override
Future<void> close([bool force = true]) async {
// No resources to clean up in this simple handler
}
}
Example Framework Adapter
class MyFrameworkHandler implements RequestHandler {
final MyFramework framework;
HttpServer? _server;
MyFrameworkHandler(this.framework);
@override
Future<void> handleRequest(HttpRequest request) async {
return framework.processRequest(request);
}
@override
Future<int> startServer({int port = 0}) async {
_server = await HttpServer.bind(InternetAddress.loopbackIPv4, port);
_server!.listen(handleRequest);
return _server!.port;
}
@override
Future<void> close([bool force = true]) async {
await _server?.close(force: force);
_server = null;
}
}
- Implementers
Constructors
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
close(
[bool force = true]) → Future< void> - Releases any resources used by this handler.
-
handleRequest(
HttpRequest request) → Future< void> - Handles an HTTP request directly.
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
startServer(
{int port = 0}) → Future< int> - Starts a server on the given port (for server-based transports).
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited