const http = require('http') class LikeExpress { constructor() { this.middleList = [] this.routes = { all: [], get: [], post: [] } } // 处理参数 register(path) { const info = {} const slice = Array.prototype.slice if (typeof path === 'string') { info.path = path info.stack = slice.call(arguments, 1) } else { info.path = '/' info.stack = slice.call(arguments, 0) } return info } use() { const info = this.register.apply(this, arguments) this.routes.all.push(info) } get() { const info = this.register.apply(this, arguments) this.routes.get.push(info) } post() { const info = this.register.apply(this, arguments) this.routes.post.push(info) } match(url, method) { let stack = [] if (url === 'favicon.ico') { return stack } let curRoutes = [] curRoutes = curRoutes.concat(this.routes.all).concat(this.routes[method]) curRoutes.forEach(route => { if (url.indexOf(route.path) === 0) { stack = stack.concat(route.stack) } }) return stack } handle(list, req, res) { const next = () => { const middware = list.shift() if (middware) { middware(req, res, next) } } next() } callback() { return (req, res) => { res.json = data => { res.setHeader('Content-Type', 'application/json') res.end(JSON.stringify(data)) } const url = req.url const method = req.method.toLowerCase() const resultList = this.match(url, method) this.handle(resultList, req, res) } } listen(...args) { const server = http.createServer(this.callback()) server.listen(...args) } } module.exports = LikeExpress
来源:https://www.cnblogs.com/raind/p/11826759.html