Skip to content

Instantly share code, notes, and snippets.

@iggymacd
Created April 30, 2012 18:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save iggymacd/2560928 to your computer and use it in GitHub Desktop.
Save iggymacd/2560928 to your computer and use it in GitHub Desktop.
Sample FileHandler
class FileHandler {
FileHandler(){
}
void onRequest(HttpRequest request, HttpResponse response, [String fileName = null]){
final int BUFFER_SIZE = 4096;
if (fileName == null) {
fileName = request.path.substring(1);
}
File file = new File(fileName);
if (file.existsSync()) {
String mimeType = "text/html; charset=UTF-8";
int lastDot = fileName.lastIndexOf(".", fileName.length);
if (lastDot != -1) {
String extension = fileName.substring(lastDot);
if (extension == ".css") { mimeType = "text/css"; }
if (extension == ".js") { mimeType = "application/javascript"; }
if (extension == ".ico") { mimeType = "image/vnd.microsoft.icon"; }
if (extension == ".png") { mimeType = "image/png"; }
}
response.headers.set("Content-Type", mimeType);
// Get the length of the file for setting the Content-Length header.
RandomAccessFile openedFile = file.openSync();
response.contentLength = openedFile.lengthSync();
openedFile.closeSync();
// Pipe the file content into the response.
file.openInputStream().pipe(response.outputStream);
} else {
print("File not found: $fileName");
new NotFoundHandler().onRequest(request, response);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment