dart-lang / shelf

Web server middleware for Dart
https://pub.dev/packages/shelf
BSD 3-Clause "New" or "Revised" License
921 stars 124 forks source link

add the possibility to specify a regular expression as route #400

Open insinfo opened 9 months ago

insinfo commented 9 months ago

add the possibility to specify a regular expression as route my use case is this simple app that I have a Rest API and in the "/storage/" endpoint I want to serve static files


void _startServer(List args) async {
  String address = args[1] as String;
  int port = args[2];

  final app = Router();
//define other routes of app
  routes(app);

  final staticFileHandler = createStaticHandler('storage');
// today's workaroud
  app.all(r'/storage/<file|.*>', (Request rec, String file) {  
    print('staticFileHandler ${rec.url}');
    final pathSegments = [...rec.url.pathSegments]..removeAt(0);  
    rec.url.replace(pathSegments: pathSegments);
    return staticFileHandler(rec); 
  });

  final handler = Pipeline()
      .addMiddleware(corsHeaders())
      .addMiddleware(logRequests())
      .addHandler(app);

  final server = await io.serve(handler, address, port, shared: true);
  server.defaultResponseHeaders.remove('X-Frame-Options', 'SAMEORIGIN');
  print('Serving at http://${server.address.host}:${server.port}');
}
import 'package:shelf_router/shelf_router.dart';

void main() {
  final app = Router();

  // Define a route using a regular expression
  app.all(RegExp(r'^/storage.*'), (Request request) {
    // Handle the route logic here
    return Response.ok('Matched /storage route');
  });

  // Start the server
  // ...

  // Example: Match URLs
  print(app.canRoute(Request('GET', '/storage/file.txt'))); // Should print true
  print(app.canRoute(Request('GET', '/storage/images/photo.jpg'))); // Should print true
  print(app.canRoute(Request('GET', '/other-route'))); // Should print false
}