Skip to content
Browse files

Routing urls.

  • Loading branch information...
1 parent 4f09c46 commit f433f5e0ec8a32e4e7a41946f0d6fc2690761282 @athoune committed
Showing with 47 additions and 18 deletions.
  1. +21 −18 app.js
  2. +26 −0 lib/router.js
View
39 app.js
@@ -1,5 +1,6 @@
var http = require('http'),
net = require('net'),
+ Router = require('./lib/router').Router,
State = require('./lib/state').State,
tcp_socket = require('./lib/input/tcp_socket');
@@ -7,27 +8,29 @@ process.title = 'metricsd';
function conf(key, defaultValue) {
return process.env[key] | defaultValue;
-};
+}
var state = new State();
-http.createServer(function (req, res) {
- if(req.url === "/events") {
- res.writeHead(200, { 'Content-Type': 'text/event-stream'});
- var write_event = function(evt) {
- res.write('data: ');
- res.write(evt);
- res.write("\r\n\r\n");
- };
- write_event(state.as_json());
- state.on('set', function(key, value) {
- write_event(JSON.stringify({key:value}));
- });
- } else {
- res.writeHead(200, {'Content-Type': 'application/json'});
- res.end(state.as_json());
- }
-}).listen(
+var server = http.createServer();
+var router = new Router(server);
+router.route(/^\/events/, function(req, res) {
+ res.writeHead(200, { 'Content-Type': 'text/event-stream'});
+ var write_event = function(evt) {
+ res.write('data: ');
+ res.write(evt);
+ res.write("\r\n\r\n");
+ };
+ write_event(state.as_json());
+ state.on('set', function(key, value) {
+ write_event(JSON.stringify({key:value}));
+ });
+});
+router.route(/^\/data/, function(req, res) {
+ res.writeHead(200, {'Content-Type': 'application/json'});
+ res.end(state.as_json());
+});
+server.listen(
conf('METRICS_HTTP_PORT', 1337),
conf('METRICS_HTTP_HOST', 'localhost'));
View
26 lib/router.js
@@ -0,0 +1,26 @@
+var Router = function(server) {
+ this.server = server;
+ this.routes = [];
+ var that = this;
+ server.on('request', function(req, res) {
+ for (var i = 0; i < that.routes.length; i++) {
+ var line = that.routes[i];
+ var pattern = line[0];
+ var cb = line[1];
+ var m = pattern.exec(req.url);
+ if (m) {
+ cb(req, res);
+ break;
+ }
+ }
+ res.writeHead(404, {'Content-Type': 'text/plain'});
+ res.end('Not found');
+ });
+};
+
+exports.Router = Router;
+
+/** Add a route */
+Router.prototype.route = function(pattern, cb) {
+ this.routes.push([pattern, cb]);
+};

0 comments on commit f433f5e

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