Skip to content

Instantly share code, notes, and snippets.

@ithinkihaveacat
Created February 23, 2010 00:13
Show Gist options
  • Save ithinkihaveacat/311695 to your computer and use it in GitHub Desktop.
Save ithinkihaveacat/311695 to your computer and use it in GitHub Desktop.
From 5c1b089a11c900c9345c798887e59056f215af43 Mon Sep 17 00:00:00 2001
From: Michael Stillwell <mjs@beebo.org>
Date: Mon, 22 Feb 2010 23:33:17 +0000
Subject: [PATCH] Enhance http.createServer() so that if multiple functions are provided as
arguments, each function is added as a request listener. i.e.
http.createServer(m1, m2);
will arrange for both m1 and m2 to be called and passed request and response
objects when a request is received.
---
lib/http.js | 7 +++-
test/mjsunit/test-http-multi-listeners.js | 42 +++++++++++++++++++++++++++++
2 files changed, 47 insertions(+), 2 deletions(-)
create mode 100644 test/mjsunit/test-http-multi-listeners.js
diff --git a/lib/http.js b/lib/http.js
index 6278b71..31714f5 100644
--- a/lib/http.js
+++ b/lib/http.js
@@ -412,11 +412,14 @@ function flushMessageQueue (connection, queue) {
return false;
}
-
exports.createServer = function (requestListener, options) {
var server = new process.http.Server();
//server.setOptions(options);
- server.addListener("request", requestListener);
+ for (var i = 0; i < arguments.length; i++) {
+ if (typeof arguments[i] === 'function') {
+ server.addListener("request", arguments[i]);
+ }
+ }
server.addListener("connection", connectionListener);
return server;
};
diff --git a/test/mjsunit/test-http-multi-listeners.js b/test/mjsunit/test-http-multi-listeners.js
new file mode 100644
index 0000000..66e79d3
--- /dev/null
+++ b/test/mjsunit/test-http-multi-listeners.js
@@ -0,0 +1,42 @@
+process.mixin(require("./common"));
+http = require("http");
+PORT = 8888;
+
+// m1 sets the content-type
+
+function m1(req, res) {
+ res.writeHeader(200, {'content-type': 'text/plain'});
+}
+
+// m2 sets the body
+
+function m2(req, res) {
+ var body = "";
+ req.addListener("data", function(s) { body += s; });
+ req.addListener("end", function() {
+ res.write("Hello, " + body);
+ res.close();
+ });
+}
+
+var server = http.createServer(m1, m2);
+server.listen(PORT);
+
+var client = http.createClient(PORT);
+
+var body = "Clem";
+var req = client.request("PUT", "/", { 'content-length': body.length });
+
+req.addListener('response', function (res) {
+ assert.equal(200, res.statusCode);
+ assert.equal("text/plain", res.headers['content-type']);
+ var body = "";
+ res.addListener('data', function (chunk) { body += chunk; });
+ res.addListener('end', function() {
+ assert.equal("Hello, Clem", body);
+ server.close();
+ });
+});
+
+req.write(body);
+req.close();
\ No newline at end of file
--
1.7.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment