router.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 method = 'index';
  22. let handlerFile;
  23. if(path=='/'){
  24. handlerFile = '/index.js'
  25. }else if(path.lastIndexOf('/')==(path.length-1)){
  26. handlerFile = `${path}index.js`;
  27. }else{
  28. if(FILE.existsSync(Core.Path.Handler + `${path}.js`)){
  29. handlerFile = `${path}.js`;
  30. }else{
  31. let pathArr = path.split('/');
  32. method = pathArr.pop();
  33. path = pathArr.join('/');
  34. if(FILE.existsSync(Core.Path.Handler + `${path}.js`)){
  35. handlerFile = `${path}.js`;
  36. }
  37. }
  38. }
  39. if(!handlerFile) return Router._error('No such handler ['+path+']',res);
  40. handlerFile = Core.Path.Handler + handlerFile;
  41. if(method=='__construct') return Router._error('__construct can\'t be called outside in ['+handlerFile+']',res);
  42. let handler;
  43. try {
  44. handler = require(handlerFile);
  45. }catch(e){
  46. LOGGER.debug(e.stack,res);
  47. }
  48. if(typeof handler === 'function') handler = new handler();
  49. let baseClass = new HANDLER(req,res);
  50. let newHandlerClass = Object.assign(baseClass,handler);
  51. if(!CACHE.router[handlerFile]){ CACHE.router[handlerFile] = true;}
  52. if(newHandlerClass.COOKIE && newHandlerClass.COOKIE['session']){
  53. new SESSION.instance(newHandlerClass.COOKIE['session'],function(sessionid,session){
  54. newHandlerClass.session = session;
  55. Router.runHandler(path,handlerFile,newHandlerClass,method,res);
  56. });
  57. }else{
  58. new SESSION.instance(null,function(sessionid,session){
  59. newHandlerClass.session = session;
  60. newHandlerClass.setCookie('session',sessionid,'forever','/');
  61. Router.runHandler(path,handlerFile,newHandlerClass,method,res);
  62. });
  63. }
  64. },
  65. runHandler:function(path,handlerFile,handler,method,res){
  66. if(RouterRule && RouterRule[path] && RouterRule[path]['permission'].length){
  67. let status = handler.session.get('status');
  68. if(!new RegExp(status).exec(RouterRule[path]['permission'])){
  69. let control = (RouterRule[path]['onerror']).split(':');
  70. let way = control[0];
  71. let output = control[1];
  72. if(way=='R'){
  73. if(!output) output = '/';
  74. return handler.endRedirect(output);
  75. }
  76. if(way=='A'){
  77. if(!output) output = 'Unauthorized';
  78. return handler.endAPI(-1,output);
  79. }
  80. }
  81. }
  82. if(handler.hasOwnProperty(method) && typeof handler[method]==='function'){
  83. let noBypass = true;
  84. if(handler.hasOwnProperty('__construct') && typeof handler['__construct']==='function') noBypass = handler['__construct']();
  85. if(noBypass || noBypass===undefined) handler[method]();
  86. }else{
  87. Router._error('Handler ['+handlerFile+'] no such method "'+method+'"',res);
  88. }
  89. },
  90. _error:function(log,res){
  91. LOGGER.error(log);
  92. res.writeHead(404, {'Content-Type': 'text/html'});
  93. res.end('404');
  94. }
  95. };
  96. module.exports = function(req,res){
  97. let URI = req.url;
  98. let URLParse = URL.parse(URI,true);
  99. let URLArr = URLParse.pathname.split('/');
  100. let enterURI = String(URLArr[1])==''?'index':String(URLArr[1]);
  101. let isAsset = (enterURI == Config.Asset.asset_path || URI=='/favicon.ico');
  102. req._GET = URLParse.query;
  103. if(isAsset){
  104. let assetPath = URLArr.join('/').replace('/'+Config.Asset.asset_path,'');
  105. Router.goAsset(assetPath,req,res);
  106. return;
  107. }
  108. req._Cookie = {};
  109. req.headers.cookie && req.headers.cookie.split(';').forEach(function(Cookie){
  110. let parts = Cookie.split('=');
  111. let key = parts[0].trim();
  112. let value = (parts[1]||'').trim();
  113. if(parts.length>2){
  114. parts = parts.shift();
  115. value = parts.join('=').trim();
  116. }
  117. req._Cookie[key] = value;
  118. });
  119. Router.goHandler(URLParse.pathname,req,res);
  120. return this;
  121. };