
Dart Shelf Package
Dart Shelf is a package for building web servers and other HTTP-based services in the Dart programming language. It provides a simple, consistent API for working with HTTP requests and responses, and is designed to be easy to use and easy to extend.
One of the key features of Shelf is its routing system, which allows developers to easily map URLs to specific handlers. This is done using a combination of “handlers” and “middleware”, which are Dart functions that are called when a particular URL is requested.
Here is an example of a simple Shelf-based server that returns “Hello, World!” for any request:
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
void main() {
var handler = const shelf.Pipeline()
.addMiddleware(shelf.logRequests())
.addHandler(_echoRequest);
io.serve(handler, 'localhost', 8080).then((server) {
print('Serving at http://${server.address.host}:${server.port}');
});
}
shelf.Response _echoRequest(shelf.Request request) {
return new shelf.Response.ok('Hello, World!');
}
In the example above, the _echoRequest
function is the handler that will be called for any incoming request, and it returns a shelf.Response
object with the message "Hello, World!". The shelf.Pipeline
class is used to create a series of middleware that will be called before the handler, in this case, the logRequests()
middleware which is used for logging the requests.
Another feature of Shelf is that it allows developers to easily add middleware to the request handling pipeline. Middleware functions are called in the order in which they are added, and can be used to perform tasks such as logging, authentication, and error handling. Here is an example of how to add middleware that logs the request headers:
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
void main() {
var handler = const shelf.Pipeline()
.addMiddleware(shelf.logRequests())
.addMiddleware(_logHeaders)
.addHandler(_echoRequest);
io.serve(handler, 'localhost', 8080).then((server) {
print('Serving at http://${server.address.host}:${server.port}');
});
}
shelf.Response _echoRequest(shelf.Request request) {
return new shelf.Response.ok('Hello, World!');
}
shelf.Middleware _logHeaders(shelf.Handler innerHandler) {
return (shelf.Request request) {
print('Headers: ${request.headers}');
return innerHandler(request);
};
}
In this example, the _logHeaders
function is added as middleware in the pipeline using addMiddleware
method, it will be called before the _echoRequest
handler, and it logs the headers of the incoming request.
Dart Shelf is a powerful and flexible package for building web servers and other HTTP-based services.