index.js 1.9 KB

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