/** * @Author HonorLee (dev@honorlee.me) * @Version 1.0 (2018-05-04) * @License MIT */ 'use strict' CACHE.router = {}; var Router ={ goAsset:function(path,req,res){ let assetFile = Core.Path.Asset+path; FILE.stat(assetFile,function(err,status){ if(err || !status.isFile()){ Router._error('No such file ['+path+']',res); }else{ STATIC.load(assetFile,req,res); } }); }, goHandler:function(path,req,res){ let pathArr = path.split('/'); let method = 'index'; let match = false; if(path=='/') path = '/index'; let expArr = [],methodMark = {}; let handlerFile; // handlerFile = path + '/index.js'; expArr.push(handlerFile); methodMark[handlerFile] = 'index'; // handlerFile = path + '.js'; expArr.push(handlerFile); methodMark[handlerFile] = 'index'; // if(path!='/index'){ method = pathArr.pop(); handlerFile = pathArr.join('/') + '/index.js'; expArr.push(handlerFile); methodMark[handlerFile] = method; // handlerFile = pathArr.join('/') + '.js'; expArr.push(handlerFile); methodMark[handlerFile] = method; } match = new RegExp(expArr.join('|')).exec(CACHE.HandlersString); if(!match) return Router._error('No such handler ['+handlerFile+']',res); method = methodMark[match]; handlerFile = Core.Path.Handler + match; let handler; try { handler = require(handlerFile); }catch(e){ Router._error(e.stack,res); } let baseClass = new HANDLER(req,res); let newHandlerClass = Object.assign(baseClass,handler); if(!CACHE.router[handlerFile]){ CACHE.router[handlerFile] = true;} if(newHandlerClass.hasOwnProperty(method) && typeof newHandlerClass[method]==='function'){ let noBypass = true; if(newHandlerClass.hasOwnProperty('__construct') && typeof newHandlerClass['__construct']==='function') noBypass = newHandlerClass['__construct'](); if(noBypass || noBypass===undefined) newHandlerClass[method](); }else{ Router._error('Handler ['+handlerFile+'] no such method "'+method+'"',res); } }, _error:function(log,res){ LOGGER.error(log); res.writeHead(404, {'Content-Type': 'text/html'}); res.end('404'); } }; module.exports = function(req,res){ let URI = req.url; let URLParse = URL.parse(URI,true); let URLArr = URLParse.pathname.split('/'); let enterURI = String(URLArr[1])==''?'index':String(URLArr[1]); let isAsset = enterURI == Config.Asset.asset_path; req._GET = URLParse.query; if(isAsset){ let assetPath = URLArr.join('/').replace('/'+Config.Asset.asset_path,''); Router.goAsset(assetPath,req,res); return; } req._Cookie = {}; req.headers.cookie && req.headers.cookie.split(';').forEach(function(Cookie){ let parts = Cookie.split('='); let key = parts[0].trim(); let value = (parts[1]||'').trim(); if(parts.length>2){ parts = parts.shift(); value = parts.join('=').trim(); } req._Cookie[key] = value; }); Router.goHandler(URLParse.pathname,req,res); return this; };