waffle
Version:
シンプルなWEBアプリケーションフレームワークです。(ALL YOUR NODE ARE BELONG TO US)
68 lines (61 loc) • 2.55 kB
JavaScript
/*
* Copyright 2012 Katsunori Koyanagi
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* @overview 静的コンテンツを返すコントローラのファクトリです。
*/
;
var Server = require("node-static").Server;
/**
* 静的コンテンツを返すコントローラを作成して返します。この簡易サーバは開発目的のもので、本運用での利用は推奨しません。
* 本来は静的コンテンツに特化したNginxなどのフロントエンドを組み合わせるべきです。
* <p>
* パスのパターンに括弧を使用することで、そのマッチ結果のインデックスの1番目の要素をリクエストパスとみなすことができます。
* 通常"/contents/.*"に対して、"./public"を指定すると、"./public/contents/"からファイルを参照します。
* しかし、"/contents/(.*)"にすることで、"./public/"からファイルを参照することができます。
* </p>
*
* @example <code>
* var waffle = require("waffle");
* config.router.on("/contents/(.*)", waffle.entensions.staticContents("./public"));
* </code>
* @function
* @name Extensions#staticContents
* @param {String}
* rootDir アプリケーションルートを起点とした静的コンテンツのルートディレクトリ
* @return {Function} コントローラ
*/
module.exports = function(rootDir) {
var server;
return function(context) {
if (server == null) {
server = new Server(context.app.approot + "/" + rootDir);
}
var original = context.req.url;
if (context.matches && context.matches[1]) {
context.req.url = "/" + context.matches[1];
}
server.serve(context.req, context.res,
function(error, res) {
if (error && error.status >= 400) {
context.error(error.status, error.status + " "
+ error.message);
return;
}
context.complete();
});
context.req.url = original;
};
};