1 /** 2 * Contains convenience functions for pre-formatted HTTP responses. 3 * Note that all functions here will flush the response, meaning that you do 4 * not have to manually flush the response in your handler. 5 */ 6 module handy_httpd.responses; 7 8 import handy_httpd.response; 9 10 /** 11 * Convenience method to prepare a simple 200 OK response. 12 * Params: 13 * response = The HTTP response to write to. 14 */ 15 void okResponse(ref HttpResponse response) { 16 response.setStatus(200).setStatusText("OK").flushHeaders(); 17 } 18 19 /** 20 * Convenience method to send a file response to a request. 21 * Params: 22 * response = The HTTP response to write to. 23 * filename = The filename to send. 24 * type = The mime type to send, such as "text/html; charset=utf-8" 25 */ 26 void fileResponse(ref HttpResponse response, string filename, string type) { 27 import std.file; 28 import std.stdio; 29 import std.conv : to; 30 if (!exists(filename)) { 31 response.setStatus(404).setStatusText("Not Found") 32 .addHeader("Content-Type", type).flushHeaders(); 33 } else { 34 response.setStatus(200).setStatusText("OK") 35 .addHeader("Content-Type", type); 36 auto file = File(filename, "r"); 37 ulong size = file.size(); 38 response.addHeader("Content-Length", size.to!string).flushHeaders(); 39 // Flush the headers, and begin streaming the file directly. 40 foreach (ubyte[] buffer; file.byChunk(16_384)) { 41 response.clientSocket.send(buffer); 42 } 43 } 44 } 45 46 void notFound(ref HttpResponse response) { 47 response.setStatus(404).setStatusText("Not Found").flushHeaders(); 48 } 49 50 /** 51 * Convenience method to send a method not allowed response. 52 * Params: 53 * response = The response to write to. 54 */ 55 void methodNotAllowed(ref HttpResponse response) { 56 response.setStatus(405).setStatusText("Method Not Allowed").flushHeaders(); 57 }