router.js 2.7 KB

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