简易版koa

173 阅读1分钟

只是实现了koa里的use和listen----未完待续



const http = require('http');
let age = 100;

class myKoa {
  constructor() {
    this.context = {};
    this.useCallback = null;
  }

  listen(host) {
    const server = http.createServer(this.callback.bind(this));
    return server.listen(host);
  }

  async callback(req, res) {
    await this.useCallback(this.context, this.next.bind(this));
    const { body = '' } = this.context;
    res.end(body);
  }

  use(callback) {
    this.useCallback = callback;
    return this;
  }

  next() {
    console.log(this, '-----');
  }
}

const app = new myKoa();

app.use(async (ctx, next) => {
  await next();
  console.log('user-----');
  age++;
  ctx.body = JSON.stringify({ name: '张三', age, grade: 'dfsa' });
});

app.listen(8000);
console.log('running');