UNPKG

809 BJavaScriptView Raw
1module.exports = Router
2
3function Router () {
4 this.routes = []
5 this._default = noop
6 this.match = this.match.bind(this)
7}
8
9Router.prototype.route = function (regex, handler) {
10 if (regex === '*') {
11 this._default = handler
12 } else {
13 this.routes.push({
14 regex: regex,
15 handler: handler
16 })
17 }
18}
19
20Router.prototype.default = function (handler) {
21 this._default = handler
22}
23
24Router.prototype.match = function (req, res, next) {
25 var url = req.url
26 var len = this.routes.length
27 var i = 0
28 var output, route
29 for (; i < len; i++) {
30 route = this.routes[i]
31 output = route.regex.exec(url)
32
33 if (output) {
34 route.handler(req, res, output, next)
35 return
36 }
37 }
38
39 this._default(req, res, next)
40}
41
42function noop (req, res) {
43 res.statusCode = 404
44 res.end()
45}