Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

migrated meryl to node version 0.4.x and refactored some parts with s…

…ome rewriting
  • Loading branch information...
commit c86f5aeaa091a02e0226592993c5df2fc5486c3a 1 parent afeb9d3
@kadirpekel authored
View
63 README.md
@@ -1,46 +1,47 @@
Meryl
=====
-Meryl is minimalist web framework for nodejs platform.
+Meryl is a minimalist web framework for nodejs platform.
It is really simple to use, fun to play and easy to modify.
Here is simple preview.
+ // take the pills
var meryl = require('meryl');
- meryl
- .plug('GET *', function (req, resp, next) {
- resp.headers.server = 'Meryl on NodeJS';
- next();
- }
- )
- .plug('GET /private/*', function (req, resp, next) {
- resp.status = 401;
- throw 'Forbidden';
- }
- )
- .handle('GET /', function (req, resp) {
- resp.send('<h3>Hello, World!</h3>');
- }
- )
- .handle('GET /greet/{name}', function (req, resp) {
- resp.send('<h3>Hello, ' + req.params.name + '</h3>');
- }
- )
- .run();
-
-Meryl has much more...
-
-Please visit Meryl homepage for all related stuff.
-
-<http://coffeemate.github.com/meryl>
-
-For updates please follow: <http://twitter.com/meryljs>
+ // first, take it easy
+ meryl.handle('GET /', function (req, resp) {
+ resp.end('<h3>Hello, World!</h3>');
+ });
+
+ // not impressed? let it interfere with blood some more
+ meryl.handle('GET /greet/{who}', function(req, resp) {
+ resp.render('greeter_template', {name: req.params.who});
+ });
+
+ // lay down and enjoy it
+ meryl.plug('GET *', function(req, resp, next) {
+ resp.setHeader('server', 'meryl');
+ next();
+ });
+
+ // now you are a 'meryl' junkie
+ meryl.run();
+
+
+Meryl has much more.
+
+Please visit wiki page for documentation:
+ <http://github.com/coffeemate/meryl/wiki>
+
+Also there are plenty of examples in 'examples' directory:
+ <http://github.com/coffeemate/meryl/tree/master/examples>
+
+For updates please follow:
+ <http://twitter.com/meryljs>
Contributors:
* Kadir Pekel (Author) <http://twitter.com/kadirpekel>
* George Stagas <http://twitter.com/stagas>
* Samuel Morello <http://twitter.com/ouvanous>
- * Tom R <http://twitter.com/rx>
-
View
12 examples/advanced/app.js
@@ -11,29 +11,29 @@ require('http').createServer(
.plug(function (req, resp, next) {
resp.filteredSend = function (buffer) {
- resp.send("<h1>" + buffer.toString() + "</h1>");
+ resp.end("<h1>" + buffer.toString() + "</h1>");
};
next();
})
.plug(function (req, resp, next) {
- resp.headers.server = 'node';
+ resp.setHeader('server', 'node');
console.log(req.method + ' ' + req.params.pathname);
next();
})
.plug('POST *', function (req, resp, next) {
- resp.status = 405;
+ resp.statusCode = 405;
throw new Error('method not allowed');
})
.plug('{method} /private/*', function (req, resp, next) {
- resp.status = 401;
+ resp.statusCode = 401;
throw new Error('access denied');
})
.handle('GET /', function (req, resp) {
- resp.send("<h1>Demonstraing Meryl</h1>");
+ resp.end("<h1>Demonstraing Meryl</h1>");
})
.handle('GET /{pagename}.html', function (req, resp) {
@@ -41,7 +41,7 @@ require('http').createServer(
})
.handle('GET /exception', function (req, resp) {
- resp.send(1);
+ resp.end(1);
})
.cgi({debug: true})
View
2  examples/blog-mvc/app.js
@@ -12,7 +12,7 @@ var controllerDir = 'controllers',
datastore.load(function () {
// Register plugins
- meryl.plug(connect.staticProvider({root: staticDir}), connect.logger());
+ meryl.plug(connect.static(staticDir), connect.logger());
// Loads controllers automatically
var loadControllers = function (controllerDir, onLoad) {
View
2  examples/blog-mvc/controllers/home.js
@@ -5,7 +5,7 @@ with (meryl) {
});
get('/about', function(req, resp) {
- resp.send('<h3>Meryl is simple to use, fun to play, easy to modify!</h3>');
+ resp.end('<h3>Meryl is simple to use, fun to play, easy to modify!</h3>');
});
}
View
2  examples/coffeekup-template/app.coffee
@@ -6,7 +6,7 @@ people = ['animal', 'beakers', 'piggy', 'kermit']
(require '../../index')
.plug connect.logger(),
- connect.staticProvider()
+ connect.static(".")
.get '/', (req, resp) ->
resp.redirect('/people')
View
6 examples/connect/app.js
@@ -4,17 +4,17 @@ var Connect = require('connect'),
meryl
.p(
function (req, resp, next) {
- resp.headers.server = 'nodejs/connect/meryl';
+ resp.setHeader('backend', 'nodejs/connect/meryl');
next();
},
Connect.logger()
)
.p('GET *',
Connect.favicon(),
- Connect.staticProvider()
+ Connect.static(".")
)
.h('GET /', function (req, resp) {
- resp.send("<h1>Welcome To NodeJS!</h1><img src='nodejs.png' />");
+ resp.end("<h1>Welcome To NodeJS!</h1><img src='nodejs.png' />");
})
.run();
View
2  examples/dust-template/app.js
@@ -63,7 +63,7 @@ meryl
if (err) {
throw err;
}
- resp.send(output);
+ resp.end(output);
});
};
next();
View
2  examples/fabby/app.js
@@ -2,7 +2,7 @@ with (require('connect')) {
require('../../index') // meryl
.fabby
- (logger(), staticProvider())
+ (logger(), static("."))
('GET /', function (req, resp) {
resp.render('home');
}
View
2  examples/helloworld/app.js
@@ -2,7 +2,7 @@ var meryl = require('../../index');
meryl
.h('GET /', function (req, resp) {
- resp.send("<h1>Hello World!</h1>");
+ resp.end("<h1>Hello World!</h1>");
})
.run();
View
2  examples/paperboy/app.js
@@ -13,7 +13,7 @@ meryl
});
})
.h('GET /', function (req, resp) {
- resp.send("<h1>Welcome To NodeJS!</h1><img src='nodejs.png' />");
+ resp.end("<h1>Welcome To NodeJS!</h1><img src='nodejs.png' />");
})
.run();
View
2  examples/standalone/boot.js
@@ -7,5 +7,5 @@ module.exports = function (meryl) {
meryl.options.templateExt = '.mt', // Default is '.jshtml'
- meryl.plug(connect.staticProvider(), connect.logger());
+ meryl.plug(connect.static("."), connect.logger());
};
View
2  examples/twinkler/app.js
@@ -4,7 +4,7 @@ var meryl = require('../../index'),
var twinkles = ['This is my freaking first wink', 'Hey tweeting sucks, lets twinkle'];
-meryl.p(Connect.staticProvider({root: 'public'}));
+meryl.p(Connect.static('public'));
meryl.h('GET /', function (req, resp) {
resp.render('index', {twinkles: twinkles});
View
208 lib/meryl.js
@@ -12,12 +12,13 @@ var sys = require('sys'),
url = require('url'),
fs = require('fs'),
path = require('path');
-
+
+
/**
* Default encoding
*/
var __encoding = 'utf-8';
-
+
/*
* Merges two objects. Source object overrides to destination
*
@@ -135,10 +136,10 @@ Meryl.prototype = {
* @api private
*/
_notFoundHandler: function (req, resp) {
- if (resp.status >= 200 && resp.status < 300) {
- resp.status = 404;
+ if (resp.statusCode >= 200 && resp.statusCode < 300) {
+ resp.statusCode = 404;
}
- resp.send('<h3>Not Found</h3><pre>' + req.params.pathname + '</pre>');
+ resp.end('<h3>Not Found</h3><pre>' + req.params.pathname + '</pre>');
},
/*
@@ -150,10 +151,10 @@ Meryl.prototype = {
* @api private
*/
_errorHandler: function (req, resp, e) {
- if (resp.status >= 200 && resp.status < 300) {
- resp.status = 500;
+ if (resp.statusCode >= 200 && resp.statusCode < 300) {
+ resp.statusCode = 500;
}
- resp.send('<h3>Server error</h3><pre>' +
+ resp.end('<h3>Server error</h3><pre>' +
((e instanceof Error && this.options.debug) ? e.stack : e) + '</pre>');
},
@@ -259,6 +260,46 @@ Meryl.prototype = {
},
/*
+ * A simple factory to able to create multiple
+ * distinct Meryl instances outside module
+ */
+ factory: function () {
+ return new Meryl();
+ },
+
+ /*
+ * Shorthand helper function for running Meryl
+ * instantly using inner cgi
+ * @param {Number} port
+ * @param {String} hostname
+ * @api public
+ */
+ run: function (opts) {
+ var server = http.createServer(this.cgi(opts));
+ server.listen(this.options.port || process.env.PORT || 3000,
+ this.options.hostname || process.env.HOSTNAME || 'localhost');
+ return server;
+ },
+
+ /*
+ * Funny helper function for constructing Meryl applications
+ * in (fab) flavored style
+ */
+ fabby: function () {
+ var self = this;
+ function contextCarrier() {
+ if (!arguments.length ||
+ (arguments.length === 1 && typeof arguments[0] === 'object')) {
+ return self.run(arguments[0]);
+ } else {
+ self.plug.apply(self, arguments);
+ return contextCarrier;
+ }
+ }
+ return contextCarrier.apply(self, arguments);
+ },
+
+ /*
* Main entry point of Meryl. It pushes some initial
* preperations for handling http requests.
*
@@ -271,9 +312,7 @@ Meryl.prototype = {
*/
cgi: function (opts) {
var self = this;
-
- opts = Object.merge(opts || {}, self.options);
-
+ self.options = Object.merge(opts || {}, self.options);
var infra = self.plugins.concat(self.handlers);
infra.push({pattern: '* <templatename>', cb: function (req, resp, next) {
try {
@@ -286,53 +325,16 @@ Meryl.prototype = {
}
}
}});
+
infra.push({pattern: '*', cb: self._notFoundHandler});
return function (req, resp) {
- resp.status = 200;
- resp.headers = {'content-type': 'text/html'};
-
- resp.send = function (data, encoding) {
- if (!this.headers.hasOwnProperty('content-length')) {
- this.headers['content-length'] = data ? data.length : 0;
- }
- this.writeHead(this.status, this.headers);
- this.end(data, encoding || __encoding);
- };
-
- resp.redirect = function (location) {
- this.status = 301;
- this.headers.location = location;
- this.send();
- };
-
- function render(templateName, data) {
- templateName = templateName || '/';
- templateName = templateName.replace(/\.\.+/, '\\.', 'g');
-
- data = data || {};
- data.request = req;
- data.response = resp;
- data.render = render;
-
- if (templateName[templateName.length - 1] === '/') {
- templateName += 'index';
- }
- var templatePath = path.join(process.cwd(),
- opts.templateDir, templateName + self.options.templateExt);
- var src = null;
- try {
- src = fs.readFileSync(templatePath, __encoding);
- } catch (e) {
- throw 'template not found';
- }
- return src ? opts.templateFunc(src, data) : null;
- }
-
- resp.render = function (templateName, data) {
- return this.send(render(templateName, data));
- };
-
+ // Set default status code
+ resp.statusCode = 200;
+ // Also default content-type
+ resp.setHeader('content-type', 'text/html');
+ req.meryl = resp.meryl = self;
+ resp.request = req;
req.params = url.parse(req.url, true);
req.addListener('data', function (data) {
if (!req.postdata) {
@@ -344,50 +346,65 @@ Meryl.prototype = {
self._proc(infra, self, req, resp);
});
};
- },
-
- /*
- * A simple factory to able to create multiple
- * distinct Meryl instances outside module
- */
- factory: function () {
- return new Meryl();
- },
-
- /*
- * Shorthand helper function for running Meryl
- * instantly using inner cgi
- * @param {Number} port
- * @param {String} hostname
- * @api public
- */
- run: function (opts) {
- var server = http.createServer(this.cgi(opts));
- server.listen(this.options.port || process.env.PORT || 3000,
- this.options.hostname || process.env.HOSTNAME || 'localhost');
- return server;
- },
-
- /*
- * Funny helper function for constructing Meryl applications
- * in (fab) flavored style
- */
- fabby: function () {
- var self = this;
- function contextCarrier() {
- if (!arguments.length ||
- (arguments.length === 1 && typeof arguments[0] === 'object')) {
- return self.run(arguments[0]);
- } else {
- self.plug.apply(self, arguments);
- return contextCarrier;
- }
- }
- return contextCarrier.apply(self, arguments);
}
};
/*
+ * Extend http.ServerResponse to add simple http redirecting helper
+ *
+ * Examples:
+ *
+ * resp.redirect('/another_page');
+ *
+ * @param {String} location
+ * @api public
+ */
+http.ServerResponse.prototype.redirect = function (location) {
+ this.writeHead(301, {'Location': location});
+ this.end();
+};
+
+/*
+ * Extend http.ServerResponse to add template rendering feature.
+ * The first argument 'templateName' is the name of template without file extension.
+ * The default template extension is 'jshtml'. You can change it by
+ * configuring 'meryl' options. The second argument 'ctx' is the context object
+ * which is used as a data holder while rendering given template
+ *
+ * Examples:
+ *
+ * resp.render('templateNameWithoutExt', {myvar: 'myvalue'})
+ *
+ * @param {String} templateName
+ * @param {Object} ctx
+ * @api public
+ */
+http.ServerResponse.prototype.render = function (templateName, ctx) {
+ var self = this;
+ function render(templateName, data) {
+ templateName = templateName || '/';
+ templateName = templateName.replace(/\.\.+/, '\\.', 'g');
+ data = data || {};
+ data.request = self.request;
+ data.response = self;
+ data.render = render;
+ if (templateName[templateName.length - 1] === '/') {
+ templateName += 'index';
+ }
+ var templatePath = path.join(process.cwd(),
+ self.meryl.options.templateDir, templateName + self.meryl.options.templateExt);
+ var src = null;
+ try {
+ src = fs.readFileSync(templatePath, __encoding);
+ } catch (e) {
+ throw 'template not found';
+ }
+ return src ? self.meryl.options.templateFunc(src, data) : null;
+ }
+ return this.end(render(templateName, ctx));
+};
+
+/*
* Shorthand meryl functions for http methods
*/
['get', 'post', 'put', 'delete'].forEach(function (method) {
@@ -410,4 +427,3 @@ process.on('uncaughtException', function (err) {
* export Meryl as a pre-instantiated instance
*/
module.exports = new Meryl();
-
View
4 package.json
@@ -1,11 +1,11 @@
{ "readme": "http://github.com/coffeemate/meryl#readme"
-, "version": "0.9.8"
+, "version": "1.0.1"
, "description": "Minimalist web framework for NodeJS"
, "main": "index"
, "author": "Kadir Pekel <kadirpekel@gmail.com>"
, "name": "meryl"
, "bin": {"meryl": "./lib/cli.js"}
-, "engines": { "node": ">=0.1.101" }
+, "engines": { "node": ">=0.4.0" }
, "repository" :
{
"type": "git"
View
22 test/test-meryl.js
@@ -20,8 +20,8 @@ exports.testCustomtNotFoundHandler = function (test) {
httputil(
meryl()
.handleNotFound(function (req, resp) {
- resp.status = 405;
- resp.send('test data');
+ resp.statusCode = 405;
+ resp.end('test data');
}
)
.cgi(),
@@ -59,8 +59,8 @@ exports.testCustomErrorHandler = function (test) {
httputil(
meryl()
.handleError(function (req, resp, err) {
- resp.status = 501;
- resp.send(err);
+ resp.statusCode = 501;
+ resp.end(err);
}
)
.h('GET /', function (req, resp) {
@@ -83,31 +83,31 @@ exports.testPluginChaining = function (test) {
httputil(
meryl()
.p(function (req, resp, next) {
- resp.headers.plugin1 = true;
+ resp.setHeader('plugin1', true);
next();
})
.p('*', function (req, resp, next) {
- resp.headers.plugin2 = true;
+ resp.setHeader('plugin2', true);
next();
})
.p('GET *', function (req, resp, next) {
- resp.headers.plugin3 = true;
+ resp.setHeader('plugin3', true);
next();
})
.p('GET /', function (req, resp, next) {
- resp.headers.plugin4 = true;
+ resp.setHeader('plugin4', true);
next();
})
.p('GET /private', function (req, resp, next) {
- resp.status = 403;
+ resp.statusCode = 403;
throw new Error();
})
.p('POST /', function (req, resp, next) {
- resp.headers.plugin5 = true;
+ resp.setHeader('plugin5', true);
next();
})
.h('GET /', function (req, resp) {
- resp.send('test data');
+ resp.end('test data');
})
.cgi(),
function (server, client) {
View
2  test/test-method.js
@@ -6,7 +6,7 @@ var meryl = require('./../index').factory,
httputil(
meryl()
.h(val + ' /', function (req, resp) {
- resp.send(req.method);
+ resp.end(req.method);
})
.cgi(),
function (server, client) {
View
20 test/test-router.js
@@ -6,8 +6,8 @@ exports.testSinglePathVar = function (test) {
httputil(
meryl()
.h('GET /{param1}', function (req, resp) {
- resp.headers['content-type'] = 'application/json';
- resp.send(JSON.stringify(req.params));
+ resp.setHeader('content-type', 'application/json');
+ resp.end(JSON.stringify(req.params));
})
.cgi(),
function (server, client) {
@@ -48,8 +48,8 @@ exports.testSingleGreedyPathVar = function (test) {
httputil(
meryl()
.h('GET /<param1>', function (req, resp) {
- resp.headers['content-type'] = 'application/json';
- resp.send(JSON.stringify(req.params));
+ resp.setHeader('content-type', 'application/json');
+ resp.end(JSON.stringify(req.params));
})
.cgi(),
function (server, client) {
@@ -83,8 +83,8 @@ exports.testMultiplePathVars = function (test) {
httputil(
meryl()
.h('GET /{param1}/{param2}/{param3}', function (req, resp) {
- resp.headers['content-type'] = 'application/json';
- resp.send(JSON.stringify(req.params));
+ resp.setHeader('content-type', 'application/json');
+ resp.end(JSON.stringify(req.params));
})
.cgi(),
function (server, client) {
@@ -127,8 +127,8 @@ exports.testMultipleGreedyPathVars = function (test) {
httputil(
meryl()
.h('GET /<param1>/<param2>', function (req, resp) {
- resp.headers['content-type'] = 'application/json';
- resp.send(JSON.stringify(req.params));
+ resp.setHeader('content-type', 'application/json');
+ resp.end(JSON.stringify(req.params));
})
.cgi(),
function (server, client) {
@@ -163,8 +163,8 @@ exports.testMixedTypesOfPathVars = function (test) {
httputil(
meryl()
.h('GET /{param1}/<param2>/{param3}', function (req, resp) {
- resp.headers['content-type'] = 'application/json';
- resp.send(JSON.stringify(req.params));
+ resp.setHeader('content-type', 'application/json');
+ resp.end(JSON.stringify(req.params));
})
.cgi(),
function (server, client) {

0 comments on commit c86f5ae

Please sign in to comment.
Something went wrong with that request. Please try again.