作為一個好的Restfull Api不僅在於service url的語義,可讀性,冪等,正交,作為http狀態碼也很重要,一個好的Http Status Code給使用者一個很好的響應,比如200表示正常成功,201表示創建成功,409沖突,404資源不存在等等。所以在做一個基於node.js+mongodb+angularjs的demo時發現node.js express沒有提供相應的輔助類,但是本人不喜歡將201,404這類毫無語言層次語義的東西到處充斥着,所以最后決定自己寫一個,但是同時本人也很懶,不喜歡做重復的苦力活,怎么辦?那就從我最熟悉的c#中HttpStatusCode枚舉中copy出來吧,最后為了簡便在mac上所以采用了利用node.js去解析msdn關於httpstatuscode的文檔生成node.js的輔助類。
代碼很簡單:
1 var http = require('http'); 2 3 var fs = require('fs'); 4 5 var $ = require('jquery'); 6 7 var output = "httpStatusCode/index.js"; 8 9 (function(){ 10 11 12 13 String.format = function() { 14 15 var s = arguments[0]; 16 17 for (var i = 0; i < arguments.length - 1; i++) { 18 19 var reg = new RegExp("\\{" + i + "\\}", "gm"); 20 21 s = s.replace(reg, arguments[i + 1]); 22 23 } 24 25 return s; 26 27 }; 28 29 30 31 32 var options = { 33 34 host:'msdn.microsoft.com', 35 36 port:80, 37 38 path:'/zh-cn/library/system.net.httpstatuscode.aspx' 39 40 }; 41 42 43 44 45 http.get(options,function (response) { 46 47 var html = ""; 48 49 response.on("data",function (chunk) { 50 51 html += chunk; 52 53 }).on("end", function () { 54 55 handler(html); 56 57 }).on('error', function (e) { 58 59 console.log("Got error: " + e.message); 60 61 }); 62 63 64 65 66 function getHttpStatusCode(htmlString) { 67 68 var $doc = $(html); 69 70 var rows = $doc.find("table#memberList tr:gt(0)"); 71 72 var status = {}; 73 74 rows.each(function(i,row){ 75 76 status[$(row).find("td:eq(1)").text()] = 77 78 parseInt($(row).find("td:eq(2)").text().match(/\d+/).toString()); 79 80 }); 81 82 return status; 83 84 }; 85 86 87 88 function generateCode(status){ 89 90 var code = ""; 91 92 code += "exports.httpStatusCode = " + JSON.stringify(status) + ";"; 93 94 return code; 95 96 }; 97 98 99 100 function writeFile(code){ 101 102 fs.writeFile(output, code, function(err) { 103 104 if(err) { 105 106 console.log(err); 107 108 } else { 109 110 console.log("The file was saved " + output + "!"); 111 112 } 113 114 }); 115 116 }; 117 118 119 120 121 function handler(html){ 122 123 var status = getHttpStatusCode(html); 124 125 var code = generateCode(status); 126 127 writeFile(code); 128 129 }; 130 131 132 133 134 }); 135 136 })();
代碼寄宿在github:https://github.com/greengerong/node-httpstatuscode
最終生成類為:

1 exports.httpStatusCode = { 2 "Continue": 100, 3 "SwitchingProtocols": 101, 4 "OK": 200, 5 "Created": 201, 6 "Accepted": 202, 7 "NonAuthoritativeInformation": 203, 8 "NoContent": 204, 9 "ResetContent": 205, 10 "PartialContent": 206, 11 "MultipleChoices": 300, 12 "Ambiguous": 300, 13 "MovedPermanently": 301, 14 "Moved": 301, 15 "Found": 302, 16 "Redirect": 302, 17 "SeeOther": 303, 18 "RedirectMethod": 303, 19 "NotModified": 304, 20 "UseProxy": 305, 21 "Unused": 306, 22 "TemporaryRedirect": 307, 23 "RedirectKeepVerb": 307, 24 "BadRequest": 400, 25 "Unauthorized": 401, 26 "PaymentRequired": 402, 27 "Forbidden": 403, 28 "NotFound": 404, 29 "MethodNotAllowed": 405, 30 "NotAcceptable": 406, 31 "ProxyAuthenticationRequired": 407, 32 "RequestTimeout": 408, 33 "Conflict": 409, 34 "Gone": 410, 35 "LengthRequired": 411, 36 "PreconditionFailed": 412, 37 "RequestEntityTooLarge": 413, 38 "RequestUriTooLong": 414, 39 "UnsupportedMediaType": 415, 40 "RequestedRangeNotSatisfiable": 416, 41 "ExpectationFailed": 417, 42 "UpgradeRequired": 426, 43 "InternalServerError": 500, 44 "NotImplemented": 501, 45 "BadGateway": 502, 46 "ServiceUnavailable": 503, 47 "GatewayTimeout": 504, 48 "HttpVersionNotSupported": 505 49 };
最后考慮到或許還有很多像我一樣懶散的人,所以共享此代碼發布到了npm,只需要npm install httpstatuscode,便可以簡單實用,如下是一個測試demo:
1 var httpStatusCode = require("httpstatuscode").httpStatusCode; 2 3 var toBeEqual = function (actual,expected){ 4 5 if(actual !== expected){ 6 7 throw (actual + " not equal " + expected); 8 9 } 10 11 }; 12 13 toBeEqual(httpStatusCode.OK,200); 14 15 toBeEqual(httpStatusCode.Created,201); 16 17 toBeEqual(httpStatusCode.BadRequest,400); 18 19 toBeEqual(httpStatusCode.InternalServerError,500); 20 21 22 23 24 console.log(httpStatusCode); 25 26 console.log("success");
懶人的文章總是代碼多余文字,希望代碼能說明一切,感謝各位能閱讀此隨筆。