router.js 5.0 KB

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