diff memory_profiler_server.js @ 52:a10cb805b5ab

Added RESTful methods for memory tracking.
author Atul Varma <varmaa@toolness.com>
date Wed, 24 Jun 2009 17:47:55 -0700
parents 8750e9ecf3af
children 2b22291fa09a
line wrap: on
line diff
--- a/memory_profiler_server.js	Wed Jun 24 17:29:27 2009 -0700
+++ b/memory_profiler_server.js	Wed Jun 24 17:47:55 2009 -0700
@@ -1,5 +1,3 @@
-print("roots are " + getGCRoots());
-
 var socket = new ServerSocket();
 
 var PORT = 8080;
@@ -24,18 +22,39 @@
 
 print("Waiting for requests on port " + PORT + ".");
 
-while (1) {
+function processRequest(socket) {
   var conn = socket.accept();
 
-  if (conn) {
+  try {
     var requestHeaders = getHeaders(conn);
     if (requestHeaders == null)
-      continue;
+      return true;
     var requestLines = requestHeaders.split("\r\n");
     print(requestLines[0]);
+    var reqParts = requestLines[0].split(" ");
+    var method = reqParts[0];
+    var path = reqParts[1];
+
+    var code = "200 OK";
+    var toSend;
+
+    // TODO: We'd like to set the MIME type of JSON data to application/json,
+    // but Firefox doesn't let us browse a webserver this way, which is
+    // annoying, so we're just leaving it at text/plain for now.
+
+    if (path == "/gc-roots")
+      toSend = JSON.stringify(getGCRoots());
+
+    if (path == "/stop")
+      toSend = "Stopping server now!";
+
+    if (!toSend) {
+      code = "404 Not Found";
+      toSend = "Not found, yo.";
+    }
+
     //print("headers: " + uneval(requestHeaders));
-    var toSend = "hello there.";
-    var headerLines = ["HTTP/1.0 200 OK",
+    var headerLines = ["HTTP/1.0 " + code,
                        "Content-Type: text/plain",
                        "Connection: close",
                        "Content-Length: " + toSend.length];
@@ -45,6 +64,14 @@
     conn.send(response);
     conn.close();
     //print("response sent.");
-  } else
-    throw new Error("Unexpected: conn is " + conn);
+  } catch (e) {
+    print(e.toString());
+    try { conn.close(); } catch (e) {}
+  }
+  if (path == "/stop")
+    return false;
+  return true;
 }
+
+while (processRequest(socket)) {}
+socket.close();