ノードのhttpモジュールの上に非常に簡単なHTTPフレームワークを構築するのはかなり簡単です。
const app = new Framework({ port: 4000 });
app.get('/', (req, res) => {
res.end('Home page');
});
app.get('/about', (req, res) => {
res.end('About page');
});
app.listen(() => {
console.log('Started server!');
});
:
'use strict';
const Http = require('http');
const Url = require('url');
// Framework
const Framework = function (options) {
this.options = options;
this.routes = [];
this.listener = Http.createServer(this._onRequest.bind(this));
};
Framework.prototype.get = function (path, handler) {
this.routes.push({ path, method: 'GET', handler });
};
Framework.prototype.post = function (path, handler) {
this.routes.push({ path, method: 'POST', handler });
};
Framework.prototype.listen = function (callback) {
this.listener.listen(this.options.port, callback);
};
Framework.prototype._onRequest = function (req, res) {
// Find the first matching route
for (let i = 0; i < this.routes.length; ++i) {
const route = this.routes[i];
const url = Url.parse(req.url);
if (route.method === req.method && url.path === route.path) {
return route.handler(req, res);
}
}
// No matching routes
res.writeHead(404);
res.end('Not found');
};
あなたはそうのようなこのミニフレームワークを使用することができます。ここではapp.get()
とapp.listen()
メソッドを実装し、私が作った迅速な1だ、あなたはそれがよりエクスプレスのようなものになる育つ可能性がどのように見ることができます
あなたは、いくつかのcURLのリクエストでそれをテストすることができます。
$ curl -i http://localhost:4000/
HTTP/1.1 200 OK
Date: Sun, 24 Apr 2016 14:38:02 GMT
Connection: keep-alive
Content-Length: 9
Home page
$ curl -i http://localhost:4000/about
HTTP/1.1 200 OK
Date: Sun, 24 Apr 2016 14:38:08 GMT
Connection: keep-alive
Content-Length: 10
About page
$ curl -i http://localhost:4000/spaghetti
HTTP/1.1 404 Not Found
Date: Sun, 24 Apr 2016 14:38:14 GMT
Connection: keep-alive
Transfer-Encoding: chunked
Not found
明らかにこれは本当に基本的なフレームワークであり、多くのプロに苦しんでいますhapiのようなフレームワークが解決しました:
- パスのパラメータのサポートはありません。
/users/{id}
。 URLパスは正確に
- あなたがルートを追加する順序が重要である(これは問題につながることができます)
- 競合するパスがファイルを提供し、テンプレートをレンダリングのような素晴らしい機能(多くの不足している
- を許可されているルート・パスと一致する必要がありますハンドラーで手動で行うこともできますが)
あなたが何を求めているのかよく分かりません。 Nodeのコアhttpモジュールの上に独自のHTTPフレームワークの基本機能を実装する方法を尋ねていますか? –
@MattHarrisonは、同じ表現ロジックを作成してアプリとルートを作成し、それを聞きます。新しいアプリケーションとapp.get()app.listen() – user6246965
これらのメソッドの高速ソースコードを見ましたか? –