简述了koa2源码的大体框架结构,接下来我们来实现一个koa2的框架,笔者认为理解和实现一个koa框架需要实现四个大模块,分别是:
实现koa2的四大模块
封装nodehttpserver、创建Koa类构造函数
构造request、response、context对象
中间件机制和剥洋葱模型的实现
错误捕获和错误处理
koa2模块分析和实现
模块一:封装nodehttpserver和创建Koa类构造函数
阅读koa2的源码得知,实现koa的服务器应用和端口监听,其实就是基于node的原生代码进行了封装,如下图的代码就是通过node原生代码实现的服务器监听。
lethttp=require('http');
letserver=http.createServer((req,res)=>{
res.writeHead(200);
res.end('helloworld');
});
server.listen(3000,()=>{
console.log('listenningon3000');
});
我们需要将上面的node原生代码封装实现成koa的模式:
consthttp=require('http');
constKoa=require('koa');
constapp=newKoa();
app.listen(3000);
实现koa的第一步就是对以上的这个过程进行封装,为此我们需要创建application.js实现一个Application类的构造函数:
lethttp=require('http');
classApplication{
constructor(){
this.callbackFunc;
}
listen(port){
letserver=http.createServer(this.callback());
server.listen(port);
}
use(fn){
this.callbackFunc=fn;
}
callback(){
return(req,res)=>{
this.callbackFunc(req,res);
};
}
}
module.exports=Application;
总之,koa2的框架模块给大家了,希望大家重视。