router.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. /*
  2. * @Author: HonorLee
  3. * @Version 1.0
  4. * @LastUpdate 2018/6/19
  5. * @License MIT
  6. */
  7. 'use strict'
  8. CACHE.router = {};
  9. var Router ={
  10. goAsset:function(path,req,res){
  11. let assetFile = Core.Path.Asset+path;
  12. FILE.stat(assetFile,function(err,status){
  13. if(err || !status.isFile()){
  14. Router._error('No such file ['+path+']',res);
  15. }else{
  16. STATIC.load(assetFile,req,res);
  17. }
  18. });
  19. },
  20. goHandler:function(path,req,res){
  21. let pathArr = path.split('/');
  22. let method = 'index';
  23. let match = false;
  24. if(path=='/') path = '/index';
  25. let expArr = [],methodMark = {};
  26. let handlerFile;
  27. //
  28. handlerFile = path + '/index.js';
  29. expArr.push(handlerFile);
  30. methodMark[handlerFile] = 'index';
  31. //
  32. handlerFile = path + '.js';
  33. expArr.push(handlerFile);
  34. methodMark[handlerFile] = 'index';
  35. //
  36. if(path!='/index'){
  37. if(pathArr.length==2){
  38. method = pathArr[1];
  39. handlerFile = '/index.js';
  40. expArr.push(handlerFile);
  41. methodMark[handlerFile] = method;
  42. }else{
  43. method = pathArr.pop();
  44. handlerFile = pathArr.join('/') + '/index.js';
  45. expArr.push(handlerFile);
  46. methodMark[handlerFile] = method;
  47. //
  48. handlerFile = pathArr.join('/') + '.js';
  49. expArr.push(handlerFile);
  50. methodMark[handlerFile] = method;
  51. }
  52. }
  53. match = new RegExp(expArr.join('|')).exec(CACHE.HandlersString);
  54. if(!match) return Router._error('No such handler ['+handlerFile+']',res);
  55. method = methodMark[match];
  56. handlerFile = Core.Path.Handler + match;
  57. if(method=='') method = 'index';
  58. if(method=='__construct') return Router._error('__construct can\'t be called outside in ['+handlerFile+']',res);
  59. let handler;
  60. try {
  61. handler = require(handlerFile);
  62. }catch(e){
  63. LOGGER.debug(e.stack,res);
  64. }
  65. if(typeof handler === 'function') handler = new handler();
  66. let baseClass = new HANDLER(req,res);
  67. let newHandlerClass = Object.assign(baseClass,handler);
  68. if(!CACHE.router[handlerFile]){ CACHE.router[handlerFile] = true;}
  69. if(newHandlerClass.COOKIE && newHandlerClass.COOKIE['session']){
  70. new SESSION.instance(newHandlerClass.COOKIE['session'],function(sessionid,session){
  71. newHandlerClass.session = session;
  72. Router.runHandler(path,handlerFile,newHandlerClass,method,res);
  73. });
  74. }else{
  75. new SESSION.instance(null,function(sessionid,session){
  76. newHandlerClass.session = session;
  77. newHandlerClass.setCookie('session',sessionid,'forever','/');
  78. Router.runHandler(path,handlerFile,newHandlerClass,method,res);
  79. });
  80. }
  81. },
  82. runHandler:function(path,handlerFile,handler,method,res){
  83. if(RouterRule && RouterRule[path] && RouterRule[path]['permission'].length){
  84. let status = handler.session.get('status');
  85. if(!new RegExp(status).exec(RouterRule[path]['permission'])){
  86. let control = (RouterRule[path]['onerror']).split(':');
  87. let way = control[0];
  88. let output = control[1];
  89. if(way=='R'){
  90. if(!output) output = '/';
  91. return handler.endRedirect(output);
  92. }
  93. if(way=='A'){
  94. if(!output) output = 'Unauthorized';
  95. return handler.endAPI(-1,output);
  96. }
  97. }
  98. }
  99. if(handler.hasOwnProperty(method) && typeof handler[method]==='function'){
  100. let noBypass = true;
  101. if(handler.hasOwnProperty('__construct') && typeof handler['__construct']==='function') noBypass = handler['__construct']();
  102. if(noBypass || noBypass===undefined) handler[method]();
  103. }else{
  104. Router._error('Handler ['+handlerFile+'] no such method "'+method+'"',res);
  105. }
  106. },
  107. _error:function(log,res){
  108. LOGGER.error(log);
  109. res.writeHead(404, {'Content-Type': 'text/html'});
  110. res.end('404');
  111. }
  112. };
  113. module.exports = function(req,res){
  114. let URI = req.url;
  115. let URLParse = URL.parse(URI,true);
  116. let URLArr = URLParse.pathname.split('/');
  117. let enterURI = String(URLArr[1])==''?'index':String(URLArr[1]);
  118. let isAsset = (enterURI == Config.Asset.asset_path || URI=='/favicon.ico');
  119. req._GET = URLParse.query;
  120. if(isAsset){
  121. let assetPath = URLArr.join('/').replace('/'+Config.Asset.asset_path,'');
  122. Router.goAsset(assetPath,req,res);
  123. return;
  124. }
  125. req._Cookie = {};
  126. req.headers.cookie && req.headers.cookie.split(';').forEach(function(Cookie){
  127. let parts = Cookie.split('=');
  128. let key = parts[0].trim();
  129. let value = (parts[1]||'').trim();
  130. if(parts.length>2){
  131. parts = parts.shift();
  132. value = parts.join('=').trim();
  133. }
  134. req._Cookie[key] = value;
  135. });
  136. Router.goHandler(URLParse.pathname,req,res);
  137. return this;
  138. };