Fix routing of paths ending in '/'

Issue #18 closed
Kevin Moore created an issue

See https://github.com/kevmoo/shelf_static.dart/issues/9

For the below example, I'd expect requests to server/foo/ to be send to the static handle with a path of / instead of empty string

import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_route/shelf_route.dart' as route;
import 'package:shelf_static/shelf_static.dart' as static;

void main() {

  var staticHandler = static.createStaticHandler('static_content', defaultDocument: 'index.html');
  final routerHandler = (
      route.router()
        ..get('/foo', staticHandler)
        ..get('/', _echoRequest)
  ).handler;

  io.serve(routerHandler, '0.0.0.0', 8080).then((server) {
    print('Serving at http://${server.address.host}:${server.port}');
  });

}

shelf.Response _echoRequest(shelf.Request request) {
  return new shelf.Response.ok('Request for "${request.url}"');
}

Comments (5)

  1. Anders Holmgren repo owner

    This fails because, by default, terminal routes like 'get' must match the entire remaining path.

    Currently, methods like get do not expose the exactMatch named parameter, so you need to use the slightly more verbose add method

    import 'package:shelf/shelf.dart' as shelf;
    import 'package:shelf/shelf_io.dart' as io;
    import 'package:shelf_route/shelf_route.dart' as route;
    import 'package:shelf_static/shelf_static.dart' as static;
    
    void main() {
    
      var staticHandler = static.createStaticHandler('static_content', defaultDocument: 'index.html');
      final routerHandler = (
          route.router()
            ..add('/foo', ['GET'], staticHandler, exactMatch: false)
            ..get('/', _echoRequest)
      ).handler;
    
      io.serve(routerHandler, '0.0.0.0', 8080).then((server) {
        print('Serving at http://${server.address.host}:${server.port}');
      });
    
    }
    
    shelf.Response _echoRequest(shelf.Request request) {
      return new shelf.Response.ok('Request for "${request.url}"');
    }
    

    Note: this is even simpler to set up in mojito

    import 'package:mojito/mojito.dart';
    
    main() {
      final app = init();
    
      app.router.addStaticAssetHandler('foo', fileSystemPath: 'static_content');
    
      app.start(port: 8080);
    }
    

    with the added benefit that it will by default use pub serve in dev mode

  2. Log in to comment