diff --git a/lib/httputils.js b/lib/httputils.js index 671fa5a16554c0e36b46519611c4e774be7c9917..e34019dc3478fc7253528d5de64876d68651f346 100644 --- a/lib/httputils.js +++ b/lib/httputils.js @@ -5,63 +5,33 @@ // various little utilities to make crafting boilerplate responses // simple -exports.fourOhFour = function(resp, reason) -{ - resp.writeHead(404, {"Content-Type": "text/plain"}); - resp.write("Not Found"); - if (reason) { - resp.write(": " + reason); +function sendResponse(resp, content, reason, code) { + if (content) { + if (reason) content += ": " + reason; + } else if (reason) { + content = reason; + } else { + content = ""; } - resp.end(); -}; - -exports.serverError = function(resp, reason) -{ - resp.writeHead(500, {"Content-Type": "text/plain"}); - if (reason) resp.write(reason); - resp.end(); -}; + resp.send(content, {"Content-Type": "text/plain"}, code); +} -exports.badRequest = function(resp, reason) -{ - resp.writeHead(400, {"Content-Type": "text/plain"}); - resp.write("Bad Request"); - if (reason) { - resp.write(": " + reason); - } - resp.end(); +exports.notFound = function(resp, reason) { + sendResponse(resp, "Not Found", reason, 404); }; -exports.forbidden = function(resp, reason) -{ - resp.writeHead(403, {"Content-Type": "text/plain"}); - resp.write("Forbidden"); - if (reason) { - resp.write(": " + reason); - } - resp.end(); +exports.serverError = function(resp, reason) { + sendResponse(resp, "Server Error", reason, 500); }; -exports.throttled = function(resp, reason) -{ - resp.writeHead(429, {"Content-Type": "text/plain"}); - resp.write("Too Many Requests"); - if (reason) { - resp.write(": " + reason); - } - resp.end(); +exports.badRequest = function(resp, reason) { + sendResponse(resp, "Bad Request", reason, 400); }; -exports.jsonResponse = function(resp, obj) -{ - resp.writeHead(200, {"Content-Type": "application/json"}); - if (obj !== undefined) resp.write(JSON.stringify(obj)); - resp.end(); +exports.forbidden = function(resp, reason) { + sendResponse(resp, "Forbidden", reason, 403); }; -exports.xmlResponse = function(resp, doc) -{ - resp.writeHead(200, {"Content-Type": "text/xml"}); - if (doc !== undefined) resp.write(doc); - resp.end(); +exports.throttled = function(resp, reason) { + sendResponse(resp, "Too Many Requests", reason, 429); };