Dart web server

I know, when you think Dart you possibly think Flutter, i.e. mobile UI. However Dart is not limited to mobile. Let’s create a simple webserver using shelf 1.2.0.

First off, create a folder for our code and in there create a file with the name pubspec.yaml. This is used to store our dependencies. In this file we have the following

name: server

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  shelf: ^1.2.0
  shelf_router: ^1.0.0
  shelf_static: ^1.0.0

The ‘name’ is the name of your app – I am not being very inspiring calling mine server.

Now we’ll just copy and paste the example from Shelf. So create a file named server.dart (the name doesn’t matter, again, I was uninspiring in my choice).

So server.dart should contain the following (I’ve changed from localhost to 0.0.0.0 to access the site from another computer as this code is hosted on a headless server).

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

void main() async {
  var handler =
      const Pipeline().addMiddleware(logRequests()).addHandler(_echoRequest);

  var server = await shelf_io.serve(handler, '0.0.0.0', 8080);

  // Enable content compression
  server.autoCompress = true;

  print('Serving at http://${server.address.host}:${server.port}');
}

Response _echoRequest(Request request) =>
    Response.ok('Request for "${request.url}"');

Next we’ll want to update/get the packages, so run

dart pub get

Finally let’s run the server using

dart server.dart

If all went well a server is run up on port 8080 and accessible via your preferred web browser. This simple example can be accessed using the following (for example)

http://192.168.1.1:8080/hello

hello is just used to get a response from the server, which will look like this Request for “hello”.

Routing

The above gives us a baseline to work from. We’re going to want to route requests to alternate functions, currently requests simple go to the _echoRequest function.

We’ve actually already added the shelf_router to our pubspec, so just import the package and add the Router. We’re going to removing the handler and the _echoRequest function, so our main function looks like this now

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

void main() async {

  var app = Router();

  app.get('/hello', (Request request) {
    return Response.ok('hello-world');
  });

  app.get('/user/<user>', (Request request, String user) {
    return Response.ok('hello $user');
  });

  var server = await shelf_io.serve(app, '0.0.0.0', 8080);

  server.autoCompress = true;

  print('Serving at http://${server.address.host}:${server.port}');
}

Note: This code is basically a copy of the example on shelf_router.