1 Poltergeist.Server = (function () {
9 function Server(owner, port) {
10 this.server = require('webserver').create();
13 this.webServer = null;
17 * Starts the web server
19 Server.prototype.start = function () {
21 this.webServer = this.server.listen(this.port, function (request, response) {
22 self.handleRequest(request, response);
27 * Send error back with code and message
33 Server.prototype.sendError = function (response, code, message) {
34 response.statusCode = code;
35 response.setHeader('Content-Type', 'application/json');
36 response.write(JSON.stringify(message, null, 4));
43 * Send response back to the client
48 Server.prototype.send = function (response, data) {
49 console.log("RESPONSE: " + JSON.stringify(data, null, 4).substr(0, 200));
51 response.statusCode = 200;
52 response.setHeader('Content-Type', 'application/json');
53 response.write(JSON.stringify(data, null, 4));
59 * Handles a request to the server
64 Server.prototype.handleRequest = function (request, response) {
66 if (request.method !== "POST") {
67 return this.sendError(response, 405, "Only POST method is allowed in the service");
69 console.log("REQUEST: " + request.post + "\n");
71 commandData = JSON.parse(request.post);
72 } catch (parseError) {
73 return this.sendError(response, 400, "JSON data invalid error: " + parseError.message);
76 return this.owner.serverRunCommand(commandData, response);