shelf
shelf copied to clipboard
feat: mount should support dynamic routes
As a developer, I want to be able to mount routes to a dynamic prefix so that I can have a consistent way to structure my router and apply middleware.
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';
final _router = Router()..mount('/<echo>', (r) => _echoHandler()(r));
Handler _echoHandler() {
var pipeline = const Pipeline();
final router = Router()..get('/', (_) => Response.ok('hi'));
return pipeline.addHandler(router);
}
void main(List<String> args) async {
final ip = InternetAddress.anyIPv4;
final handler = Pipeline().addMiddleware(logRequests()).addHandler(_router);
final port = int.parse(Platform.environment['PORT'] ?? '8080');
final server = await serve(handler, ip, port);
print('Server listening on port ${server.port}');
}
I expect to be able to run the above server and make a GET
request to http://localhost:8080/hello
and get a 200 response with hi
.
Instead, running the above code and making a GET request to http://localhost:8080/hello
results in a 500 internal server error
ERROR - 2022-07-04 15:16:20.694525
GET /hello
Error thrown by handler.
RangeError (start): Invalid value: Not in inclusive range 0..5: 8
package:shelf/src/request.dart 258:20 Request.change
package:shelf_router/src/router.dart 163:32 Router.mount.<fn>
package:shelf_router/src/router_entry.dart 105:30 RouterEntry.invoke.<fn>
package:shelf_router/src/router_entry.dart 103:30 RouterEntry.invoke.<fn>
package:shelf_router/src/router_entry.dart 111:7 RouterEntry.invoke
package:shelf_router/src/router.dart 183:38 Router.call
Related to https://github.com/google/dart-neats/issues/40
@felangel I made a PR for this functionality in case you want to give it a try. #288
@felangel I made a PR for this functionality in case you want to give it a try. #288
Thanks I'll take a look shortly 💯
EDIT
I played with the branch and the changes appear to behavior as expected. I'll plan to test the changes more thoroughly in the coming days.