backend process for doing dns lookups & http reqs.
authorRecursive Madman <[email protected]>
Sun, 15 Mar 2015 15:26:33 +0000 (15 16:26 +0100)
committerRecursive Madman <[email protected]>
Sun, 15 Mar 2015 15:26:33 +0000 (15 16:26 +0100)
backend.js [new file with mode: 0644]

diff --git a/backend.js b/backend.js
new file mode 100644 (file)
index 0000000..890797b
--- /dev/null
@@ -0,0 +1,65 @@
+
+var http = require('http');
+var dns = require('dns');
+
+var HEADERS = {
+  'Content-Type': 'application/json',
+  'Access-Control-Allow-Origin': '*'
+};
+
+http.createServer(function(req, res) {
+  var url = require('url').parse(req.url, true);
+  if(req.method === 'GET' && url.pathname === '/uri-info') {
+    console.log('query', url.query);
+    lookup(url.query, function(result) {
+      res.writeHead(200, HEADERS);
+      res.write(JSON.stringify(result));
+      res.end();
+    });
+  } else if(req.method === 'POST' && url.pathname === '/send') {
+    console.log('send request', url.query);
+    var request = http.request(url.query);
+    request.on('response', function(response) {
+      console.log('have response');
+      var body = '', lastLength = 0;
+      response.on('data', function(chunk) {
+        body += chunk;
+        if((body.length - lastLength) > 1024) {
+          console.log((body.length / 1024).toFixed(2) + ' kB');
+          lastLength = body.length;
+        }
+      });
+      response.on('end', function() {
+        console.log('end');
+        res.writeHead(200, HEADERS);
+        res.write(JSON.stringify({
+          status: response.statusCode,
+          body: body,
+          headers: response.headers
+        }));
+        res.end();
+      });
+    });
+    request.end();
+  } else {
+    res.writeHead(404, HEADERS);
+    res.write('Not Found');
+    res.end();
+  }
+}).listen(8088);
+console.log('listening on 0.0.0.0:8088');
+
+function lookup(query, callback) {
+  if(query.host) {
+    dns.resolve(query.host, function(error, result) {
+      if(error) {
+        query.error = error;
+      } else {
+        query.addresses = result;
+      }
+      callback(query);
+    });
+  } else {
+    callback(query);
+  }
+}