aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKamil Cholewiński <harry666t@gmail.com>2013-01-15 22:26:38 +0100
committerKamil Cholewiński <harry666t@gmail.com>2013-01-15 22:26:38 +0100
commit50f2597cf7741013dd491fe4da768a04b9e6c00d (patch)
treef4dbc00855b568df8901114ac0aa9e8507e082af
parent32fa9002adfdda00a42253bfc195c61b3d8bea1d (diff)
downloadfunkylisp-50f2597cf7741013dd491fe4da768a04b9e6c00d.zip
funkylisp-50f2597cf7741013dd491fe4da768a04b9e6c00d.tar.gz
funkylisp-50f2597cf7741013dd491fe4da768a04b9e6c00d.tar.bz2
miniapp, a quick&dirty web framework
-rw-r--r--miniapp.js67
1 files changed, 67 insertions, 0 deletions
diff --git a/miniapp.js b/miniapp.js
new file mode 100644
index 0000000..26b751d
--- /dev/null
+++ b/miniapp.js
@@ -0,0 +1,67 @@
+
+var url = require("url");
+
+var routes = {};
+
+function error_not_found(request) {
+ return {
+ status: 404,
+ text: "404 Not Found: " + url.parse(request.url).pathname,
+ };
+}
+
+function error_method_not_allowed(request) {
+ return {
+ status: 405,
+ text: "405 Method Not Allowed: " + request.method,
+ };
+}
+
+function route(method, url, handler) {
+ if (routes[url] === undefined)
+ routes[url] = {};
+ routes[url][method] = handler;
+}
+
+function get_handler(method, url) {
+ if (routes[url] === undefined)
+ return error_not_found;
+ if (routes[url][method] === undefined)
+ return error_method_not_allowed;
+ return routes[url][method];
+}
+
+function run(request, response) {
+ try {
+ handler = get_handler(
+ request.method,
+ url.parse(request.url).pathname
+ );
+ var result = handler(request);
+ if (result.headers === undefined)
+ result.headers = {};
+ if (result.headers["Content-Type"] === undefined)
+ result.headers["Content-Type"] = (
+ result.html !== undefined? "text/html" :
+ result.text !== undefined? "text/plain" :
+ result.json !== undefined? "application/json" :
+ result.type !== undefined? result.type :
+ undefined
+ );
+ response.writeHead(result.status || 200, result.headers);
+ response.write(
+ result.html !== undefined? result.html :
+ result.text !== undefined? result.text :
+ result.json !== undefined? JSON.stringify(result.json) :
+ result.data !== undefined? result.data :
+ ""
+ );
+ } catch (e) {
+ response.writeHead(500, {"Content-Type": "text/plain"});
+ response.write("500 Internal Server Error: " + e);
+ }
+ response.end();
+};
+
+exports.route = route;
+exports.run = run;