router.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. if(typeof handler['__construct']==='function') handler['__construct'](req,res);
  41. handler[method](req,res);
  42. }else{
  43. Router._error('Handler ['+handlerFile+'] no such method "'+method+'"',res);
  44. }
  45. }catch(e){
  46. Router._error(e.stack,res);
  47. }
  48. },
  49. _error:function(log,res){
  50. LOGGER.error(log);
  51. res.writeHead(404, {'Content-Type': 'text/html'});
  52. res.end('404');
  53. }
  54. };
  55. module.exports = function(req,res){
  56. let URI = req.url=='/'?'/index':req.url;
  57. let URLParse = URL.parse(URI,true);
  58. let URLArr = URLParse.pathname.split('/');
  59. let enterURI = String(URLArr[1])==''?'index':String(URLArr[1]);
  60. let isAsset = enterURI == Config.asset_path;
  61. req._GET = URLParse.query;
  62. if(isAsset){
  63. let assetPath = URLArr.join('/').replace('/'+Config.asset_path,'');
  64. Router.goAsset(assetPath,req,res);
  65. return;
  66. }
  67. req._Cookie = {};
  68. req.headers.cookie && req.headers.cookie.split(';').forEach(function(Cookie){
  69. let parts = Cookie.split('=');
  70. let key = parts[0].trim();
  71. let value = (parts[1]||'').trim();
  72. if(parts.length>2){
  73. parts = parts.shift();
  74. value = parts.join('=').trim();
  75. }
  76. req._Cookie[key] = value;
  77. });
  78. Router.goHandler(URLParse.pathname,req,res);
  79. return this;
  80. };