-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
executable file
·325 lines (316 loc) · 7.85 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
var HTTP = require('http');
var Path = require('path');
var QS = require('querystring');
var Fs = require('fs');
var view = require('liteview');
var llog = require('./log');
var log = llog.create({},{});
// global Log Object, injuct
Log = {
get:function(){
return llog.create({},{});
}
};
/***********************
extends http.response
************************/
HTTP.ServerResponse.prototype.setCookie = function(name,value,options){
};
HTTP.ServerResponse.prototype.redirect = function(path){
this.statusCode = 302;
this.setHeader('location','');
this.end();
};
HTTP.ServerResponse.prototype.render = function(tpl,object){
this.end(view.render(tpl,object));
};
HTTP.ServerResponse.prototype.json = function(object){
this.end(JSON.stringify(object));
};
HTTP.ServerResponse.prototype.jsonp = function(vars,object){
this.end(vars+'('+JSON.stringify(object)+');');
};
/***********************
extends http.request
************************/
HTTP.IncomingMessage.prototype.getRouter = function(){
var query = this.__querypath;
if(query.action) return query;
var arr = query.split('/');
var ctrl = arr[1];
var action = arr[2];
this.__querypath = {
controller: ctrl,
action : action,
param : arr.slice(3)
};
return this.__querypath;
};
HTTP.IncomingMessage.prototype.getCookie = function(){
};
HTTP.IncomingMessage.prototype.getPost = function(cb,noparse){
var len = this.headers['content-length'];
var post_buf,offset;
if(len === undefined){
var tmp;
//log.error('req.getPost() do not support post in chunk!');
this.on('data',function(chunk){
if(post_buf){
len = post_buf.length + chunk.length;
tmp = new Buffer(len);
post_buf.copy(tmp,0,0,post_buf.length);
chunk.copy(tmp,post_buf.length,0,chunk.length);
post_buf = tmp;
}else{
post_buf = chunk;
}
});
}else{
post_buf = new Buffer( parseInt(len,10) );
offset = 0;
this.on('data',function(chunk){
chunk.copy(post_buf,offset,0,chunk.length);
offset += chunk.length;
});
}
var self = this;
this.on('end',function(){
post_buf = post_buf.toString();
if(!noparse)post_buf = QS.parse(post_buf);
if(cb)
cb(post_buf);
else
self.emit('post',post_buf);
});
};
/** TODO **/
HTTP.IncomingMessage.prototype.getMultiPartPost = function(){
};
/** TODO **/
HTTP.IncomingMessage.prototype.getQuery = function(){
if(!this.__querystr) return {};
if(typeof this.__querystr === 'string'){
this.__querystr = QS.parse(this.__querystr);
}
return this.__querystr;
};
/**
cfg = {
listen:80 , [needed]
}
**/
function Server(cfg){
this.cfg = this.prepareCfg(cfg);
this.root = cfg.root;
this.routermap = {};
this.filtermap = function(){};
this.serv = null;
if(cfg.tpl){
view.init(cfg.tpl);
}else{
view.render = function(){return 'view is not inited ! please re-config the server .';};
}
}
Server.prototype = {
prepareCfg:function(cfg){
if( ! /^\//.test(cfg.tpl) ){
cfg.tpl = Path.join(cfg.root , cfg.tpl);
}
if( ! /^\//.test(cfg.errllog) ){
cfg.errllog = Path.join(cfg.root , cfg.errLog);
}
if( ! /^\//.test(cfg.infollog) ){
cfg.infollog = Path.join(cfg.root , cfg.infoLog);
}
return cfg;
},
view:function(cfg){
if(cfg.tpl){
view.init(cfg.tpl);
}
if(cfg.debug){
view.debug(cfg.debug);
}
if(cfg.constant){
view.constant(cfg.constant);
}
return this;
},
/** 更换 veiw 引擎 **/
setView:function(v){
if(!v.render || v.render.length < 2){
throw new Error('setView(v), view must implement view.render(tpl,obj)!');
}
view = v;
return this;
},
/** 更改log系统 **/
setLog:function(l,servLog){
if(!l.get){
throw new Error('setLog(log,servLog), log must implement Log.get("module")!');
}
if(!servLog){
throw new Error('setLog(log,servLog), servLog need , serverlog will write to this log_group!');
}
log = l.get(servLog);
Log = l;
return this;
},
/**
更改 getRouter(fn) 方法
fn : function(url){return parsedObj}
**/
setRouter:function(fn){
HTTP.IncomingMessage.prototype.getRouter = fn;
return this;
},
/**
init router info
router has two type
path match : start with / , like : /test
name match : start without / , like : 404
**/
router:function(obj){
var n = null;
var matches = {}; // match router
var named = {}; // named router
for(var i in obj){
n = i;
// router path must start with /
if(n.indexOf('/') !== 0){
named[i] = obj[i];
continue;
//throw new Error("[config error] router must start with /");
}
// remove end / from router path
if(n.match(/\/$/)) n = n.replace(/\/$/,'');
matches[i] = [
n ? new RegExp('^'+n+'\\b') : /^\/$/,
obj[i]
];
}
// add error page default
if(!named['404']){
named['404'] = function(req,res,cfg){
res.statusCode = 404;
res.end('<h2>404,Page not found!</h2>');
};
}
if(!named['500']){
named['500'] = function(req,res,cfg){
res.statusCode = 500;
res.end('<h2>500,Server error!</h2>');
};
}
this.routermap = {
matches:matches,
named:named
};
return this;
},
/**
* addfilter for request
* @param {Array} obj [description]
* @return {Object} [description]
*/
filter:function(func){
this.filtermap = func ? func : function(){};
return this;
},
/**
加载控制器控
**/
load:function(base){
var p = Path.join(this.root,base);
var controllers = Fs.readdirSync(p);
var res = {};
var name;
for(var i = 0 ; i < controllers.length ; i++){
if(controllers[i].match(/^\./)) continue;
name = controllers[i].replace(/\.js$/,'');
res[name] = require(Path.join(p,controllers[i]));
}
return res;
},
/**
start server
if cfg.port is not giving , server will not listen port
**/
start:function(cb){
var cfg = this.cfg;
this.serv = HTTP.createServer(createServerHandler(this.filtermap,this.routermap,cfg));
if(cfg.port)
this.serv.listen(cfg.port,cb);
return this;
},
getServer:function(){
return this.serv;
},
/** internal handler **/
staticFile:function(path){
var p = Path.join(this.root,path);
return function(req,res){
//TODO static server
};
},
favicon:function(path){
var p = Path.join(this.root,path);
var ico;
try{
ico = Fs.readFileSync(p);
}catch(e){
}
return function(req,res){
res.statusCode = 200;
res.end('');
};
}
};
function createServerHandler(filter,router,config){
var matches = router.matches;
var named = router.named;
config = config ? config : {};
return function(req,res){
var url = req.url,
hasQuery,
flag = false,
ft = true, //filter的返回值,true | false 退出用户请求
res_header = {'x-power' : 'liteserver(node.js)'},
i;
// remove query string
hasQuery = url.indexOf('?');
if( hasQuery !== -1 ){
req.__querystr = url.substr(hasQuery+1);
url = url.substr(0,hasQuery);
}
try{
req.__querypath = url;
// filter
ft = filter(req,res,config);
if(ft === false){
return; // if filter return false , stop response user's request
}
// router
for( i in matches ){
if(matches[i][0].test(url)){
matches[i][1](req,res,config);
flag = true;
break;
}
}
// not found page
if(!flag){
named['404'](req,res,config);
}
}catch(e){
i = flag ? i : '404';
log.error( 'controller error:' + i );
log.error(e.stack);
}
};
}
exports.createServer = function(cfg){
var server = new Server(cfg);
return server;
};
exports.Server = Server;