1
0
mirror of https://github.com/vimagick/dockerfiles.git synced 2024-12-14 11:23:02 +02:00
dockerfiles/webkit/server.js

72 lines
2.0 KiB
JavaScript
Raw Normal View History

2014-12-24 13:30:14 +02:00
#!/usr/bin/env phantomjs
2014-12-25 11:07:50 +02:00
var fs = require('fs');
var sys = require('system');
2014-12-24 13:30:14 +02:00
var server = require('webserver').create();
var parser = require('./parser');
var client = require('./client');
var utils = require('./utils');
var port;
2014-12-25 11:07:50 +02:00
if(sys.args.length > 1) {
port = parseInt(sys.args[1]);
2014-12-24 13:30:14 +02:00
} else {
port = 1024;
}
var ok = server.listen(port, function(request, response) {
if(request.method === 'POST') {
try {
var raw = request.postRaw || request.post || '{}',
req = parser.setDefaults(JSON.parse(raw));
utils.info('recv: %s', req.targetUrl);
var reqId = client.urlopen(req, function(err, res) {
if(err) {
send(response, 500, res);
} else {
send(response, 200, res);
}
});
utils.info('proc: %s (%s)', reqId, req.targetUrl);
} catch(ex) {
send(response, 400, ex);
}
2015-01-06 15:57:53 +02:00
} else if (request.method === 'GET') {
response.statusCode = 200;
response.setHeader('X-Powered-By', 'PhantomJS')
response.setHeader('Content-Type', 'text/plain')
2015-02-03 09:24:03 +02:00
response.write('Powered by PhantomJS 2.0.0');
2015-01-06 15:57:53 +02:00
response.close();
} else{
2014-12-24 13:30:14 +02:00
send(response, 405);
}
});
if(ok) {
2014-12-25 12:02:48 +02:00
var pidfile = '/var/run/webkit-' + port.toString() + '.pid';
2014-12-24 13:30:14 +02:00
utils.info('service started (listen %d)', port);
2014-12-25 11:07:50 +02:00
utils.info('write pidfile: %s (pid %d)', pidfile, sys.pid);
fs.write(pidfile, sys.pid.toString(), 'w');
2014-12-24 13:30:14 +02:00
} else {
utils.error('service failed to start');
phantom.exit(1);
}
function send(response, code, data){
if(code === 200) {
utils.info('send: %s (%d)', data.request.requestId, code);
} else {
utils.warn('send: %s (%d)', data, code);
}
response.statusCode = code;
response.setHeader('X-Powered-By', 'PhantomJS')
response.setHeader('Content-Type', 'application/json')
response.write(JSON.stringify(data || '{}'));
response.close();
}