Commits

Wes Alvaro committed 1a22df1

Initial check-in. First Node Server! w00t!

  • Participants

Comments (0)

Files changed (2)

+<!DOCTYPE html>
+<html>
+  <head>
+    <link href="//twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet">
+    <link href="//twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css" rel="stylesheet">
+    <link href="//twitter.github.com/bootstrap/assets/css/docs.css" rel="stylesheet">
+    <link href="//twitter.github.com/bootstrap/assets/js/google-code-prettify/prettify.css" rel="stylesheet">
+    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
+    <script>
+    var handleReddit = function(res) {
+      console.log(res);
+      var items = $('#items');
+      $.each(res.data.children, function(i, child) {
+        var data = child.data;
+        var li = $('<li/>', {text: data.title}).appendTo(items);
+        var imgSrc = data.thumbnail;
+        if (imgSrc !== 'default') {
+          $('<img/>', {src: data.thumbnail}).prependTo(li);
+        }
+      });
+    };
+    $(document).ready(function(){
+      var hash = location.hash.substr(1);
+      $.getJSON('//readdit.wesalvaro.c9.io/r/shutupandtakemymoney?callback=?', handleReddit);
+    });
+    </script>
+  </head>
+  <body>
+    <ul id="items"></ul>
+  </body>
+</html>
+var http = require("http");
+var url = require("url");
+var qs = require('querystring');
+
+var reddit = {
+  'hostname': 'www.reddit.com',
+  'port': 80,
+  'path': ''
+};
+
+function onRequest(request, response) {
+  var reqUrl = url.parse(request.url);
+  var pathname = reqUrl.pathname;
+  console.log("Request for " + pathname + " received.");
+  if (pathname.substr(0, 3) !== '/r/') {
+    response.end();
+    return;
+  }
+  console.log(reqUrl);
+  var query = qs.parse(reqUrl.query || '');
+  var callback = query.callback || null;
+  console.log(query);
+  reddit.path = pathname + '.json';
+  console.log(reddit.hostname + reddit.path);
+  http.get(reddit, function(res) {
+    response.writeHead(200, {'Content-Type': 'text/plain'});
+    res.setEncoding('utf8');
+    
+    if (callback) response.write(callback + '(');
+    //stream the data into the response
+    res.on('data', function (chunk) {
+      response.write(chunk);
+    });
+
+    //write the data at the end
+    res.on('end', function(){
+      if (callback) response.write(')');
+      response.end();
+    });
+    //The connection is also auto closed
+  }).on('error', function(e) {
+    response.writeHead( 500 ); //Internal server error
+    response.end( "Got error " + e); //End the request with this message
+  });
+}
+
+http.createServer(onRequest).listen(process.env.C9_PORT);
+console.log("Server has started.");