作为一个好的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");
懒人的文章总是代码多余文字,希望代码能说明一切,感谢各位能阅读此随笔。
作者:破 狼
出处:http://www.cnblogs.com/whitewolf/
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。该文章也同时发布在我的独立博客中-个人独立博客、博客园--破狼和51CTO--破狼。http://www.cnblogs.com/whitewolf/archive/2013/04/09/3009205.html