http-server.js
1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
var options = phantom.casperArgs.options;
var emit = require(options.spooky_lib + 'lib/bootstrap/emit').emit;
var port = options.port || 8080;
var JsonRpcServer = require(options.spooky_lib +
'node_modules/tiny-jsonrpc/lib/tiny-jsonrpc').Server;
var server = new JsonRpcServer();
function respond(response, code, body) {
emit('log', {
level: 'debug',
space: 'spooky.server',
message: {
event: 'response',
code: code,
body: body
}
});
response.statusCode = code;
response.write(body);
response.close();
}
require('webserver').create().
listen(port, function (request, response) {
var method = request.method.toUpperCase();
emit('log', {
level: 'debug',
space: 'spooky.server',
message: {
event: 'request',
method: method,
request: request
}
});
if (method !== 'POST') {
respond(response, 405, 'Requests must be POSTs');
return;
} else if (request.headers['Content-Type'] !== 'application/json' &&
request.headers['content-type'] !== 'application/json'
) {
respond(response, 415, 'Request entity must be JSON');
return;
}
try {
JSON.parse(request.post);
} catch (e) {
throw new Error('Could not parse "' + request.post + '" as JSON');
}
var result = JSON.parse(server.respond(request.post));
if (result.error) {
respond(response, 400, JSON.stringify(result));
} else {
respond(response, 200, JSON.stringify(result));
}
});
module.exports = server;