一個好的 RESTful API,除了 service URL 的語意、可讀性、冪等性與正交性之外,HTTP 狀態碼同樣重要。合適的狀態碼能給呼叫方清晰的回饋:200 表示正常成功,201 表示建立成功,409 表示衝突,404 表示資源不存在,等等。
所以,當我在做一個 node.js + mongodb + angularjs 的 demo 時,發現 express 並沒有提供對應的輔助類。而我實在不想讓 201、404 這類毫無語意層次的數字散落在程式碼各處,於是決定自己寫一個。
但我同時也很懶,不想做重複的苦力活。怎麼辦?那就從我最熟悉的 C# 的 HttpStatusCode 枚舉抄過來吧。最後為了省事,我乾脆在 Mac 上寫了個 node 腳本,去解析 MSDN 關於 HttpStatusCode 的文件,自動生成 node 的輔助類。
var http = require('http');
var fs = require('fs');
var $ = require('jquery');
var output = "httpStatusCode/index.js";
(function(){
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
};
var options = {
host: 'msdn.microsoft.com',
port: 80,
path: '/zh-cn/library/system.net.httpstatuscode.aspx'
};
http.get(options, function (response) {
var html = "";
response.on("data", function (chunk) {
html += chunk;
}).on("end", function () {
handler(html);
}).on('error', function (e) {
console.log("Got error: " + e.message);
});
function getHttpStatusCode(htmlString) {
var $doc = $(html);
var rows = $doc.find("table#memberList tr:gt(0)");
var status = {};
rows.each(function(i, row){
status[$(row).find("td:eq(1)").text()] =
parseInt($(row).find("td:eq(2)").text().match(/\d+/).toString());
});
return status;
};
function generateCode(status){
var code = "";
code += "exports.httpStatusCode = " + JSON.stringify(status) + ";";
return code;
};
function writeFile(code){
fs.writeFile(output, code, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved " + output + "!");
}
});
};
function handler(html){
var status = getHttpStatusCode(html);
var code = generateCode(status);
writeFile(code);
};
});
})();
程式碼放在 GitHub:https://github.com/greengerong/node-httpstatuscode
exports.httpStatusCode = {
"Continue": 100,
"SwitchingProtocols": 101,
"OK": 200,
"Created": 201,
"Accepted": 202,
"NonAuthoritativeInformation": 203,
"NoContent": 204,
"ResetContent": 205,
"PartialContent": 206,
"MultipleChoices": 300,
"Ambiguous": 300,
"MovedPermanently": 301,
"Moved": 301,
"Found": 302,
"Redirect": 302,
"SeeOther": 303,
"RedirectMethod": 303,
"NotModified": 304,
"UseProxy": 305,
"Unused": 306,
"TemporaryRedirect": 307,
"RedirectKeepVerb": 307,
"BadRequest": 400,
"Unauthorized": 401,
"PaymentRequired": 402,
"Forbidden": 403,
"NotFound": 404,
"MethodNotAllowed": 405,
"NotAcceptable": 406,
"ProxyAuthenticationRequired": 407,
"RequestTimeout": 408,
"Conflict": 409,
"Gone": 410,
"LengthRequired": 411,
"PreconditionFailed": 412,
"RequestEntityTooLarge": 413,
"RequestUriTooLong": 414,
"UnsupportedMediaType": 415,
"RequestedRangeNotSatisfiable": 416,
"ExpectationFailed": 417,
"UpgradeRequired": 426,
"InternalServerError": 500,
"NotImplemented": 501,
"BadGateway": 502,
"ServiceUnavailable": 503,
"GatewayTimeout": 504,
"HttpVersionNotSupported": 505
};
想到世上有不少和我一樣懶散的人,乾脆把這個模組發佈到了 npm。安裝只要一行:
npm install httpstatuscode
使用起來非常直觀,下面是個簡單的測試:
var httpStatusCode = require("httpstatuscode").httpStatusCode;
var toBeEqual = function (actual, expected) {
if (actual !== expected) {
throw (actual + " not equal " + expected);
}
};
toBeEqual(httpStatusCode.OK, 200);
toBeEqual(httpStatusCode.Created, 201);
toBeEqual(httpStatusCode.BadRequest, 400);
toBeEqual(httpStatusCode.InternalServerError, 500);
console.log(httpStatusCode);
console.log("success");
寫成常量的好處很直接:程式碼裡出現 httpStatusCode.NotFound 遠比裸寫 404 更能表達意圖,也比較不容易打錯數字。
懶人的文章總是程式碼多於文字,希望程式碼能說明一切。