2016-04-21 21:27:22 +00:00
|
|
|
library angel_static;
|
|
|
|
|
2016-05-02 23:11:25 +00:00
|
|
|
import 'dart:async';
|
2016-04-21 21:27:22 +00:00
|
|
|
import 'dart:io';
|
|
|
|
import 'package:angel_framework/angel_framework.dart';
|
|
|
|
import 'package:mime/mime.dart' show lookupMimeType;
|
|
|
|
|
2016-05-02 23:11:25 +00:00
|
|
|
Future<bool> _sendFile(File file, ResponseContext res) async {
|
|
|
|
res
|
|
|
|
..willCloseItself = true
|
|
|
|
..header(HttpHeaders.CONTENT_TYPE, lookupMimeType(file.path))
|
|
|
|
..status(200);
|
|
|
|
await res.streamFile(file);
|
|
|
|
await res.underlyingResponse.close();
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2016-04-21 21:27:22 +00:00
|
|
|
/// Serves files statically from a given directory.
|
2016-05-02 23:11:25 +00:00
|
|
|
RequestMiddleware serveStatic({
|
|
|
|
Directory sourceDirectory,
|
|
|
|
List<String> indexFileNames: const['index.html'],
|
|
|
|
String virtualRoot: '/'
|
|
|
|
}) {
|
2016-04-22 02:03:30 +00:00
|
|
|
if (sourceDirectory == null) {
|
|
|
|
String dirPath = Platform.environment['ANGEL_ENV'] == 'production'
|
|
|
|
? './build/web'
|
|
|
|
: './web';
|
|
|
|
sourceDirectory = new Directory(dirPath);
|
|
|
|
}
|
|
|
|
|
2016-05-02 23:11:25 +00:00
|
|
|
RegExp requestingIndex = new RegExp(r'^((\/)|(\\))*$');
|
|
|
|
|
2016-04-21 21:27:22 +00:00
|
|
|
return (RequestContext req, ResponseContext res) async {
|
|
|
|
String requested = req.path.replaceAll(new RegExp(r'^\/'), '');
|
|
|
|
File file = new File.fromUri(
|
|
|
|
sourceDirectory.absolute.uri.resolve(requested));
|
|
|
|
if (await file.exists()) {
|
2016-05-02 23:11:25 +00:00
|
|
|
return await _sendFile(file, res);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try to resolve index
|
|
|
|
String relative = req.path.replaceFirst(virtualRoot, "")
|
|
|
|
.replaceAll(new RegExp(r'^\/+'), "");
|
|
|
|
if (requestingIndex.hasMatch(relative) || relative.isEmpty) {
|
|
|
|
for (String indexFileName in indexFileNames) {
|
|
|
|
file =
|
|
|
|
new File.fromUri(sourceDirectory.absolute.uri.resolve(indexFileName));
|
|
|
|
if (await file.exists()) {
|
|
|
|
return await _sendFile(file, res);
|
|
|
|
}
|
|
|
|
}
|
2016-04-21 21:27:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|