const http = require('http')
const url = require('url')
let router = []
class Application {
get (path, handler) {
router.push({
path,
method: 'get',
handler
})
}
listen () {
http.createServer((req,res) => {
let {pathname} = url.parse(req.url, true)
for (const route of router) {
if (route.path === pathname) {
route.handler(req,res)
return
}
}
}).listen(...arguments)
}
}
module.exports = function (config) {
return new Application()
}
使用它:
const keexpress = require('./08-keexpress')
const fs = require('fs')
const path = require('path')
const app = keexpress()
app.get('/', (req,res) => {
fs.readFile(path.resolve('./index.html'),(err, data) => {
if (err) {
res.statusCode = 500
res.end('500 - Internal Server Error!')
return
}
res.statusCode = 200
res.setHeader('content-Type','text/html')
res.end(data)
})
})
app.get('/users', (req,res) => {
res.statusCode = 200
res.setHeader('content-Type', 'application/json')
res.end(JSON.stringify([{name: 'keven', age: 20}]))
})
app.listen(3001)