-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsimple-http.js
More file actions
89 lines (75 loc) · 1.92 KB
/
simple-http.js
File metadata and controls
89 lines (75 loc) · 1.92 KB
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
var Understudy = require('..');
var App = module.exports = function App() {
Understudy.call(this);
};
//
// Starts the application after running before and
// after hooks.
//
App.prototype.start = function (options, callback) {
this.perform('start', options, function (next) {
//
// Here, `options` may have been mutated from the execution
// of the before hooks.
// ...
// Do some other async thing
// ...
// These arguments are passed to the final callback unless
// short-circuited by an error here, or in an after hook.
//
next(null, options);
}, callback);
};
App.prototype.handle = function (req, res) {
req.times = {
start: process.hrtime()
};
this.perform('http:request', req, res, function (next) {
req.times.middle = process.hrtime();
req.times.begin = process.hrtime(req.times.start);
next();
}, function (err) {
if (err) {
//
// Do some error handling.
//
}
req.times.total = process.hrtime(req.times.start);
req.times.after = process.hrtime(req.times.middle);
console.log([
'Total time: %s',
' Before hooks: %s',
' After hooks: %s'
].join('\n'), format(req.times.total), format(req.times.begin), format(req.times.after));
res.end();
});
}
//
// Now we consume a new app with hooks.
//
var http = require('http');
var app = new App();
app.before('start', function (options, next) {
var server = options.server = http.createServer(function (req, res) {
app.handle(req, res);
});
server.listen(options.port, next);
});
app.after('start', function (options, next) {
console.log('App started on %s', options.port);
});
app.before('http:request', function (req, res, next) {
//
// Do something asynchronous.
//
next();
});
app.start({ port: 8080 }, function () {
console.log('ok');
});
//
// Format process.hrtime()
//
function format(s) {
return (s[0] * 1e3 + s[1] / 1e6) / 1e3;
}