index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. var mime = require('mime-types'),
  2. path = require('path'),
  3. fs = require('fs');
  4. var log = require('hlogger').createLogger('hci-http-test');
  5. function loadControllers() {
  6. var targetPath = __dirname + "/controllers";
  7. var files = fs.readdirSync(targetPath);
  8. var ret = {}
  9. for(var f of files) {
  10. if(!f.endsWith(".js")) continue;
  11. var filePath = path.join(targetPath, f);
  12. var controllerName = path.basename(f,".js");
  13. ret[controllerName] = require(filePath);
  14. };
  15. return ret;
  16. }
  17. function bundleStart(context) {
  18. var controllers = loadControllers();
  19. context.on('hci-http:stop',() => {
  20. console.log("Stopping http monitor");
  21. context.stop();
  22. });
  23. var channel = context.prefix('hci-http:req');
  24. channel.on('/monitor/api/(.*)',(req,res,e)=> {
  25. var [conName,conMethod = 'index',...params] = e.match[1].split(/\//);
  26. var con = controllers[conName];
  27. if(con == undefined || con[conMethod] == undefined) {
  28. res.statusCode = 404;
  29. return;
  30. }
  31. var to = setTimeout(function() {
  32. res.writeHead(408);
  33. res.end("Controller timeout");
  34. },5000);
  35. function cb(conRet) {
  36. clearTimeout(to);
  37. res.end(JSON.stringify(conRet));
  38. }
  39. con[conMethod](context,cb,...params);
  40. // Setting a timeout would be good
  41. });
  42. // Static server for path / monitor
  43. channel.on('/monitor/?(.*)',(req,res,e) => {
  44. if(e.count != 0) { // Something else executed
  45. return;
  46. }
  47. // Not executed
  48. //
  49. var reqroute = e.match[1];
  50. if(reqroute.length == 0) {
  51. reqroute = "index.html";
  52. }
  53. var filePath = path.join(__dirname, "/web");
  54. var fullPath = path.join(filePath, reqroute);
  55. if( fullPath.indexOf(filePath) != 0 ) {
  56. res.writeHead(400,"Permission denied");
  57. res.end("Permission denied");
  58. return;
  59. }
  60. if(!fs.existsSync(fullPath)) {
  61. res.statusCode = 404;
  62. return;
  63. }
  64. // MimeTypes??
  65. var mimeType = mime.lookup(fullPath);
  66. res.writeHead(200,{'Content-type':mimeType});
  67. var s = fs.createReadStream(fullPath);
  68. s.pipe(res);
  69. });
  70. }
  71. module.exports.bundleStart = bundleStart;