Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
insinfo opened this issue Dec 27, 2023 · 0 comments
Open

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

insinfo opened this issue Dec 27, 2023 · 0 comments

Comments

@insinfo
Copy link

insinfo commented Dec 27, 2023

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant