//HTTP服务 import HTTP = require('http'); import URL = require('url'); //表单处理器 import formidable = require('formidable') //路由控制器 import Router from './lib/router'; //模型控制器 import Module from './lib/module'; //Session控制器 import Session from './lib/session'; //控制器基类 import ControllerClass from './lib/controller'; (global as any).CONTROLLER = ControllerClass; const IncomingForm = formidable.IncomingForm; class MVC { constructor(option:{root_path:string,server_port:number}) { //定义全局MVC框架变量 const Root = `${SYSTEM.ROOTPATH}/${option.root_path}`; SYSTEM.MVC = { ROOT:Root, PORT:option.server_port, PATH:{ MODULE:`${Root}/module`, CONTROLLER:`${Root}/controller`, VIEW:`${Root}/view`, }, ROUTER_MAP:null, ROUTER:Router, SESSION:Session, EJS:require('ejs'), start:()=>{this.start()} }; //初始化Module控制器 Module.init(); //初始化MVC应用目录 Object.keys(SYSTEM.MVC.PATH).forEach((path)=>{ try{ FILE.statSync(SYSTEM.MVC.PATH[path]); }catch(e:any){ if(e.code=='ENOENT'){ FILE.mkdirsSync(SYSTEM.MVC.PATH[path]); } } }); //加载路由Map文件或初始化 const mapFile = `${SYSTEM.MVC.ROOT}/map.json`; try{ FILE.statSync(mapFile); SYSTEM.MVC.ROUTER_MAP = JSON.parse(FILE.readFileSync(mapFile,'UTF-8')); }catch(e:any){ if(e.code=='ENOENT'){ FILE.writeFileSync(mapFile,'{}','UTF-8'); }else{ LOGGER.error(`MVC Router map file [${mapFile}] parse error!`); } SYSTEM.MVC.ROUTER_MAP = {}; } } public start(){ try{ HTTP.createServer(this._serverHandler).listen(SYSTEM.MVC.PORT); LOGGER.info(`Http MVC Server start at port [${SYSTEM.MVC.PORT}]`); }catch(e:any){ LOGGER.error(`Http MVC Server start failed at port [${SYSTEM.MVC.PORT}]`); LOGGER.error(e.stack); } } protected _serverHandler(req?:HTTP.IncomingMessage,res?:HTTP.ServerResponse){ if(!req) return; const requestData:RequestData = { req,res, path:'' as string|null, refer:URL.parse(req.headers.referer||''), method:req.method?.toLowerCase()||'get', COOKIE:{} as any, GET:{}, POST:{}, UPLOAD:{}, SESSION:{} as any } // if(requestData.path==URL.parse(req.headers.referer as string,true).pathname) return; req.headers.cookie && req.headers.cookie.split(';').forEach((Cookie)=>{ const parts:Array = Cookie.split('='); let key = parts.shift(); if (key){ key = key.trim(); const value = parts.join('=').trim(); requestData.COOKIE[key] = value; } }); requestData.SESSION = new Session(requestData,requestData.COOKIE.SESSIONID); const URLParse = URL.parse(req.url as string,true); if(URLParse){ requestData.path = URLParse.pathname, requestData.GET = URLParse.query; } if(req.method && req.method.toLowerCase()=='post'){ new IncomingForm().parse(req, (err, fields, files)=>{ requestData.POST = fields; requestData.UPLOAD = files; Router.run(requestData); }); }else{ Router.run(requestData); } } } module.exports = MVC;