Created
April 30, 2012 18:39
-
-
Save iggymacd/2560928 to your computer and use it in GitHub Desktop.
Sample FileHandler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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