index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. var channel = context
  20. .channel('core-http')
  21. .on('stop',()=> {
  22. console.log("Stopping http monitor");
  23. context.stop();
  24. })
  25. .on('GET/monitor/api',(req,res,e) => {
  26. e.stop();
  27. // Manual router
  28. var re = new RegExp("/monitor/api/(.*)");
  29. var match = req.url.match(re);
  30. if(match != null) {
  31. api(match,req,res,e);
  32. return;
  33. }
  34. }).on('GET/monitor', (req,res,e) => {
  35. re = new RegExp("/monitor/?(.*)");
  36. match = req.url.match(re);
  37. if(match!=null) {
  38. staticHandler(match,req,res,e);
  39. return;
  40. }
  41. res.statusCode = 404;
  42. });
  43. //router?!
  44. function api(match,req,res,e) {
  45. var [conName,conMethod = 'index',...params] = match[1].split(/\//);
  46. var con = controllers[conName];
  47. if(con == undefined || con[conMethod] == undefined) {
  48. res.statusCode = 404;
  49. return;
  50. }
  51. var to = setTimeout(function() {
  52. res.writeHead(408);
  53. res.end("Controller timeout");
  54. },5000);
  55. function cb(conRet) {
  56. clearTimeout(to);
  57. res.end(JSON.stringify(conRet));
  58. }
  59. con[conMethod](context,cb,...params);
  60. // Setting a timeout would be good
  61. };
  62. function staticHandler(match,req,res,e) {
  63. if(e.count != 0) { // Something else executed
  64. return;
  65. }
  66. // Not executed
  67. //
  68. var reqroute = match[1];
  69. if(reqroute.length == 0) {
  70. reqroute = "index.html";
  71. }
  72. var filePath = path.join(__dirname, "/web");
  73. var fullPath = path.join(filePath, reqroute);
  74. if( fullPath.indexOf(filePath) != 0 ) {
  75. res.writeHead(400,"Permission denied");
  76. res.end("Permission denied");
  77. return;
  78. }
  79. if(!fs.existsSync(fullPath)) {
  80. res.statusCode = 404;
  81. return;
  82. }
  83. // MimeTypes??
  84. var mimeType = mime.lookup(fullPath);
  85. res.writeHead(200,{'Content-type':mimeType});
  86. var s = fs.createReadStream(fullPath);
  87. s.pipe(res);
  88. };
  89. }
  90. module.exports.bundleStart = bundleStart;