diff --git a/lib/requestHandler.js b/lib/requestHandler.js index a84ba13..0a7d736 100644 --- a/lib/requestHandler.js +++ b/lib/requestHandler.js @@ -6,6 +6,7 @@ var http = require("http"), pathUtil = require("path"), color = require("colorful"), sleep = require("sleep"), + Buffer = require('buffer').Buffer, httpsServerMgr = require("./httpsServerMgr"); var httpsServerMgrInstance = new httpsServerMgr(); @@ -30,7 +31,8 @@ function userRequestHandler(req,userRes){ var host = req.headers.host, urlPattern = url.parse(req.url), path = urlPattern.path, - ifLocalruleMatched = false; + ifLocalruleMatched = false, + callback = null; console.log(color.green("\nreceived request to : " + host + path)); /* @@ -49,6 +51,7 @@ function userRequestHandler(req,userRes){ for(var index in handleRule.map){ var rule = handleRule.map[index]; + var hostTest = new RegExp(rule.host).test(host), pathTest = new RegExp(rule.path).test(path); @@ -79,12 +82,18 @@ function userRequestHandler(req,userRes){ } } + + //sleep for seconds if configed in the rule file //see rule_sample.js if(hostTest && pathTest && !!rule.sleep){ console.log(color.yellow('[' + req.url + '] will sleep for ' + rule.sleep + ' seconds.')); sleep.sleep(rule.sleep); } + + if(hostTest && pathTest && !!rule.callback){ + callback = rule.callback; + } } if(ifLocalruleMatched){ @@ -104,7 +113,17 @@ function userRequestHandler(req,userRes){ var proxyReq = (ifHttps ? https : http).request(options, function(res) { userRes.writeHead(res.statusCode,mergeCORSHeader(req.headers,res.headers)); - res.pipe(userRes); + if(callback){ + res.on('data',function(chunk){ + userRes.write(chunk); + }); + res.on('end',function(){ + callback(userRes); + userRes.end(); + }); + }else{ + res.pipe(userRes); + } }); proxyReq.on("error",function(e){ diff --git a/rule_sample.js b/rule_sample.js index 5273e3e..9bb2221 100644 --- a/rule_sample.js +++ b/rule_sample.js @@ -19,8 +19,16 @@ var rules = { "localDir" :"/Users/Stella/tmp/" },{ "host" :/./, - "path" :/\.(js)/, + "path" :/response\.(json)/, "sleep" :5//seconds + },{ + "host" :/./, + "path" :/(.*)\.html/, + "callback" :function(res){ + //remoty.js will be inject into response via callback + res.write("