toMiddleware method

  1. @override
Middleware toMiddleware()
override

Builds the shelf middleware this value configures.

Implementation

@override
Middleware toMiddleware() {
  return (Handler inner) {
    return (Request request) async {
      final path = request.url.path;
      final normalized = _normalize(path);
      if (normalized == null) return inner(request);

      if (redirect) {
        final target = request.requestedUri.replace(path: '/$normalized');
        return Redirect.permanent(
          '${target.path}'
          '${target.hasQuery ? '?${target.query}' : ''}',
        ).intoResponse();
      }

      // `change(path:)` strips a prefix rather than rewriting the URL, so
      // the request is rebuilt at the normalized path. The body is handed on
      // unread: normalizing a path must not consume it.
      return inner(
        Request(
          request.method,
          request.requestedUri.replace(path: '/$normalized'),
          headers: request.headers,
          body: request.read(),
          context: request.context,
          protocolVersion: request.protocolVersion,
        ),
      );
    };
  };
}