Skip to content

Commit

Permalink
Add context to Response for including file and file_not_found t…
Browse files Browse the repository at this point in the history
…o be identified by other Shelf `Middleware`.
  • Loading branch information
gmpassos committed Dec 5, 2023
1 parent b3adc7c commit 7923a7f
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions pkgs/shelf_static/lib/src/static_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@ Handler createStaticHandler(String fileSystemPath,
}

if (fileFound == null) {
return Response.notFound('Not Found');
return Response.notFound(
'Not Found',
context: _buildResponseContext(fileNotFound: fileFound),
);
}
final file = fileFound;

Expand Down Expand Up @@ -120,6 +123,18 @@ Handler createStaticHandler(String fileSystemPath,
};
}

Map<String, Object>? _buildResponseContext({File? file, File? fileNotFound}) {
if (file == null && fileNotFound == null) return null;

// Ensure other Shelf `Middleware` can identify
// the processed file in the `Response` by
// including `file` and `file_not_found` in the context:
return {
if (file != null) 'shelf_static:file': file,
if (fileNotFound != null) 'shelf_static:file_not_found': fileNotFound,
};
}

Response _redirectToAddTrailingSlash(Uri uri) {
final location = Uri(
scheme: uri.scheme,
Expand Down Expand Up @@ -184,7 +199,9 @@ Future<Response> _handleFile(Request request, File file,
if (ifModifiedSince != null) {
final fileChangeAtSecResolution = toSecondResolution(stat.modified);
if (!fileChangeAtSecResolution.isAfter(ifModifiedSince)) {
return Response.notModified();
return Response.notModified(
context: _buildResponseContext(file: file),
);
}
}

Expand All @@ -199,6 +216,7 @@ Future<Response> _handleFile(Request request, File file,
Response.ok(
request.method == 'HEAD' ? null : file.openRead(),
headers: headers..[HttpHeaders.contentLengthHeader] = '${stat.size}',
context: _buildResponseContext(file: file),
);
}

Expand Down

0 comments on commit 7923a7f

Please sign in to comment.