用原生http 實現簡單 Express 框架

liangtongzhuo發表於2017-12-14

大概實現思路:封裝一個app物件,建立由(http建立)server屬性,然後建立一個stack的陣列,用來儲存use上掛載的方法。 來了來請求,判斷路徑且迴圈呼叫stack裡的方法。

app:程式碼如下

var http = require('http');
var url = require('url');
var proto = {
    stack: []
};

function createServer() {
    var app = {
        task: function(req, res) {
            app.handle(req, res);
        }
    }
    //把proto中的屬性拷貝到app物件裡
    Object.assign(app, proto);
    return app;
}
//裝載函式
proto.use = function(route, fn) {
    var path = route;
    var handle = fn;
    if (typeof route != 'string') {
        handle = route;
        path = "/";
    }
    this.stack.push({
        handle: handle,
        path: path
    });
}
//迴圈呼叫函式
proto.handle = function(req, res) {
    var stack = this.stack;
    var index = 0;

    function next(err) {
        var layer = stack[index++];
        var route = layer.path;
        var handle = layer.handle;

        var path = url.parse(req.url).pathname;
        //是否匹配路徑,是否匹配開頭
        if (path.startsWith(route)) {
            if (err) {
                if (handle.length == 4) {
                    handle(err, req, res, next);
                } else {
                    next(err);
                }
            } else {
                handle(req, res, next);
            }
        } else {
            next();
        }

    }
    next();
}

proto.listen = function(port) {
    var server = http.createServer(this.task);
    server.listen(port);
}

module.exports = createServer;

複製程式碼

git地址:https://github.com/hi363138911/express 個人部落格: http://www.liangtongzhuo.com

相關文章