Saltar al contenido principal

Shelf Dart Framework

Shelf Dart Framework: A Comprehensive Guide

Introduction​

Shelf is a powerful and flexible web framework for Dart that allows developers to quickly build web applications. It provides a simple and intuitive way to handle HTTP requests and responses, making it easy to create web APIs, server-side applications, and more. Shelf is built on top of Dart's powerful async/await syntax, which enables writing highly performant and scalable code.

History​

Shelf was first introduced in 2013 by the Dart team at Google. It was designed to be a lightweight and extensible framework for building web applications in Dart. Since its initial release, Shelf has gained popularity among Dart developers due to its simplicity, flexibility, and performance.

Features​

  1. Middleware Support: Shelf provides a middleware architecture that allows developers to easily add functionality to the request/response pipeline. Middleware can be used for tasks such as authentication, logging, compression, and more.

    import 'package:shelf/shelf.dart';

    Middleware myMiddlewareHandler = (Handler innerHandler) {
    return (Request request) {
    // Perform some pre-processing tasks
    // ...

    // Call the next handler in the pipeline
    Response response = innerHandler(request);

    // Perform some post-processing tasks
    // ...

    return response;
    };
    };
  2. Routing: Shelf provides a built-in router that allows developers to define routes and associate them with specific handler functions. This makes it easy to handle different HTTP methods and route parameters.

    import 'package:shelf/shelf.dart';
    import 'package:shelf_router/shelf_router.dart';

    var app = Router();

    app.get('/users', (Request request) {
    // Handle GET request for /users
    // ...

    return Response.ok('List of users');
    });

    app.post('/users', (Request request) {
    // Handle POST request for /users
    // ...

    return Response.ok('User created');
    });
  3. Static File Serving: Shelf provides a static file handler that allows developers to serve static files (e.g., HTML, CSS, JavaScript) directly from the file system.

    import 'package:shelf_static/shelf_static.dart';

    var staticHandler = createStaticHandler('path/to/static/files');

    var handler = Pipeline().addMiddleware(staticHandler).addHandler(app);
  4. WebSocket Support: Shelf supports WebSocket communication, allowing developers to build real-time applications and bidirectional communication between the server and client.

    import 'package:shelf_web_socket/shelf_web_socket.dart';

    var webSocketHandler = webSocketHandler((webSocket) {
    webSocket.listen((message) {
    // Handle WebSocket message
    // ...
    });
    });

    var handler = Pipeline().addMiddleware(webSocketHandler).addHandler(app);
  5. Testability: Shelf provides a test library that allows developers to easily write unit tests for their web applications. It provides utilities for creating mock requests and asserting the responses.

    import 'package:test/test.dart';
    import 'package:shelf/shelf.dart';
    import 'package:shelf_test_handler/shelf_test_handler.dart';

    void main() {
    test('Handler returns expected response', () async {
    var handler = (Request request) => Response.ok('Hello, Shelf!');

    var testHandler = TestHandler(handler);

    var response = await testHandler.get('/');

    expect(response.statusCode, equals(200));
    expect(response.readAsString(), completion(equals('Hello, Shelf!')));
    });
    }

Examples​

Let's look at a few examples to demonstrate the usage of Shelf:

Example 1: Hello World​

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

void main() {
var handler = (Request request) {
return Response.ok('Hello, World!');
};

var server = await shelf_io.serve(handler, 'localhost', 8080);
print('Server running on ${server.address}:${server.port}');
}

This example demonstrates a basic Shelf application that responds with "Hello, World!" for every request.

Example 2: JSON API​

import 'dart:convert';

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

void main() {
var handler = (Request request) {
var jsonResponse = jsonEncode({'message': 'Hello, Shelf!'});

return Response.ok(jsonResponse, headers: {'content-type': 'application/json'});
};

var server = await shelf_io.serve(handler, 'localhost', 8080);
print('Server running on ${server.address}:${server.port}');
}

This example showcases how Shelf can be used to build a JSON API. It responds with a JSON payload containing a "message" field.

Conclusion​

Shelf is a powerful and flexible web framework for Dart that provides a simple and intuitive way to build web applications. With its middleware support, routing capabilities, static file serving, WebSocket support, and testability features, Shelf offers a comprehensive solution for developing server-side applications in Dart. To learn more about Shelf and explore its full range of capabilities, visit the official Shelf documentation.