router.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict'
  2. var Router ={
  3. goAsset:function(path,req,res){
  4. let assetFile = Core.Path.Asset+path;
  5. FILE.stat(assetFile,function(err,status){
  6. if(err || !status.isFile()){
  7. Router._error('No such file ['+path+']',res);
  8. }else{
  9. STATIC.load(assetFile,req,res);
  10. }
  11. });
  12. },
  13. goHandler:function(path,req,res){
  14. let handlerFile = Core.Path.Handler + path + '.js';
  15. let method = 'index';
  16. let pathArr = path.split('/');
  17. let Res = res;
  18. let Req = req;
  19. FILE.stat(handlerFile,function(err,status){
  20. if(err || !status.isFile()){
  21. method = pathArr.pop();
  22. if(pathArr.length<=1) return Router._error('No such handler ['+handlerFile+']',Res);
  23. handlerFile = Core.Path.Handler + pathArr.join('/') + '.js';
  24. FILE.stat(handlerFile,function(err,status){
  25. if(err || !status.isFile()){
  26. Router._error('No such handler ['+handlerFile+']',Res);
  27. }else{
  28. Router.runHandler(handlerFile,method,Req,Res);
  29. }
  30. });
  31. }else{
  32. Router.runHandler(handlerFile,method,Req,Res);
  33. }
  34. });
  35. },
  36. runHandler:function(handlerFile,method,req,res){
  37. try {
  38. let handler = require(handlerFile);
  39. if(typeof handler[method]==='function'){
  40. let noBypass = true;
  41. if(typeof handler['__construct']==='function') noBypass = handler['__construct'](req,res);
  42. if(noBypass || noBypass===undefined) handler[method](req,res);
  43. }else{
  44. Router._error('Handler ['+handlerFile+'] no such method "'+method+'"',res);
  45. }
  46. }catch(e){
  47. Router._error(e.stack,res);
  48. }
  49. },
  50. _error:function(log,res){
  51. LOGGER.error(log);
  52. res.writeHead(404, {'Content-Type': 'text/html'});
  53. res.end('404');
  54. }
  55. };
  56. module.exports = function(req,res){
  57. let URI = req.url=='/'?'/index':req.url;
  58. let URLParse = URL.parse(URI,true);
  59. let URLArr = URLParse.pathname.split('/');
  60. let enterURI = String(URLArr[1])==''?'index':String(URLArr[1]);
  61. let isAsset = enterURI == Config.asset_path;
  62. req._GET = URLParse.query;
  63. if(isAsset){
  64. let assetPath = URLArr.join('/').replace('/'+Config.asset_path,'');
  65. Router.goAsset(assetPath,req,res);
  66. return;
  67. }
  68. req._Cookie = {};
  69. req.headers.cookie && req.headers.cookie.split(';').forEach(function(Cookie){
  70. let parts = Cookie.split('=');
  71. let key = parts[0].trim();
  72. let value = (parts[1]||'').trim();
  73. if(parts.length>2){
  74. parts = parts.shift();
  75. value = parts.join('=').trim();
  76. }
  77. req._Cookie[key] = value;
  78. });
  79. Router.goHandler(URLParse.pathname,req,res);
  80. return this;
  81. };