之前有寫過koa中間件的簡單使用娶眷,簡單回顧下:
//app.js
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
await next(); // 調(diào)用下一個middleware
});
app.use(async (ctx, next) => {
const start = new Date().getTime(); // 當(dāng)前時間
await next(); // 調(diào)用下一個middleware
const ms = new Date().getTime() - start; // 耗費時間
console.log(`Time: ${ms}ms`); // 打印耗費時間
});
app.use(async (ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello, koa2!</h1>';
});
app.listen(9091);
運行:
node app.js //訪問localhost:9091
以上就是koa中間件的使用届宠,可以看出中間件的執(zhí)行時通過use注冊函數(shù)豌注。知道use里執(zhí)行中間件,構(gòu)造一個服務(wù)每聪,實現(xiàn)http訪問齿风。
//server.js
const http = require('http');
class Koa{
createContent(req, res){
const ctx = {
req, res
}
return ctx;
}
callback(){
return (req, res)=>{
const ctx = this.createContent(req, res);
ctx.res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
ctx.res.end("測試http服務(wù)");
}
}
listen(port){
const server = http.createServer(this.callback());
server.listen(port);
}
}
module.exports = Koa;
//app.js
const server = require('server.js');
const app = new server();
app.listen(9000);
node app.js //執(zhí)行app, http訪問
服務(wù)核心use(中間件注冊)
//server.js
const http = require('http');
function compose(middlewares){
return function(){
function dispatch(i){
const fn = middllwares[i];
try{
return Promise.resolve(
fn(ctx, dispatch.bind(null, i+1));
);
}catch(err){
return Promise.reject(err);
}
}
dispatch(0);
}
}
class myKoa{
constructor(){
this.middleware = [];
}
use(fn){
this.middleware.push(fn);
return this;
}
createContent(req, res){
const ctx = {
req, res
}
return ctx;
}
callback(){
return (req, res)=>{
const ctx = this.createContent(req, res);
//ctx.res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
//ctx.res.end("測試http服務(wù)");
}
}
listen(port){
const server = http.createServer(this.callback());
server.listen(port);
}
}
module.exports = myKoa;
//app.js
const Iok = require('./myKoa.js');
const app = new Iok();
app.use(async (ctx, next) => {
console.log('lllll');
await next();
ctx.res.end('444444444444');
});
app.use(async (ctx) => {
console.log('222222222222');
ctx.res.end('66666666666666');
});
app.listen(9000);
以上就是實現(xiàn)koa的核心