作为一个好的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
最终生成类为:
View Code
最后考虑到或许还有很多像我一样懒散的人,所以共享此代码发布到了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/archive/2013/04/09/3009205.html,如需转载请自行联系原作者