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
| let http = require('http'); let url = require('url') function createApplication(){ let app = (req,res)=>{ let m = req.method.toLowerCase(); let { pathname } = url.parse(req.url,true) let index = 0; function next(err){ if(index === app.routes.length){ return res.end(`Cannot find ${m} ${pathname}`) } let {method, path, handler} = app.routes[index++] if(err){ if(handler.length === 4){ handler(err,req,res,next) } else { next(err) } } else { if(method === 'middle'){ if(path === '/' || path === pathname || pathname.startsWith(path+'/')){ handler(req,res,next); } else { next(); } } else { if( (method === m || method === 'all') && (path === pathname || path === '*') ){ handler(req,res) } else { next(); } } } } next(); } app.routes = []; app.use = function(path,handler){ if(typeof handler !== 'function'){ handler = path; path ='/' } let layer = { method:'middle', path, handler } app.routes.push(layer) } app.all = function(path,handler){ let layer = { method:'all', path, handler } app.routes.push(layer) } http.METHODS.forEach(method=>{ method = method.toLocaleLowerCase(); app[method] = function(path,handler){ let layer = { method, path, handler } app.routes.push(layer) } }) app.listen = function(){ let server = http.createServer(app) server.listen(...arguments) } return app; } module.exports = createApplication
|