From e1053b15d46c4333bc04d78d384b76e1aab3dd53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8A=A0=E9=87=8C?= Date: Mon, 18 Aug 2014 19:51:15 +0800 Subject: [PATCH] improve file mapping --- lib/requestHandler.js | 11 ++++++----- proxy.js | 8 ++++++-- rule_sample.js | 12 +++++++++--- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/lib/requestHandler.js b/lib/requestHandler.js index 13b258b..4c1653d 100644 --- a/lib/requestHandler.js +++ b/lib/requestHandler.js @@ -27,7 +27,7 @@ var handleRule = { function userRequestHandler(req,userRes){ var host = req.headers.host, - path = url.parse(req.url).path, + path = url.parse(req.url).pathname, ifLocalruleMatched = false; console.log(color.green("\nreceived request to : " + host + path)); @@ -47,10 +47,11 @@ function userRequestHandler(req,userRes){ console.log("==>meet the rules, will map to local file"); var targetLocalfile = rule.localFile; - if(!targetLocalfile){ //find file in dir //TODO : /a/b/c -> b/c - var basename = pathUtil.basename(path); - basename = basename.slice(0,basename.indexOf("?")); //remove chars after question mark - targetLocalfile = pathUtil.join(rule.localDir,basename); + + //localfile not set, map to dir + if(!targetLocalfile){ //find file in dir, /a/b/file.html -> dir + b/file.html + var remotePathWithoutPrefix = path.replace(new RegExp(rule.path),""); //remove prefix + targetLocalfile = pathUtil.join(rule.localDir,remotePathWithoutPrefix); } console.log("==>local file: " + targetLocalfile); diff --git a/proxy.js b/proxy.js index 79e5185..c98b9bd 100644 --- a/proxy.js +++ b/proxy.js @@ -26,9 +26,13 @@ function proxyServer(type, port, hostname,ruleFile){ self.httpProxyServer = null; - if(ruleFile){ //TODO : fs.join + if(ruleFile){ if(fs.existsSync(ruleFile)){ - requestHandler.setRules(require(ruleFile)); + try{ //for abs path + requestHandler.setRules(require(ruleFile)); //todo : require path + }catch(e){ //for relative path + requestHandler.setRules(require("./" + ruleFile)); + } console.log(color.green("rule file loaded")); }else{ console.log(color.red("can not find rule file")); diff --git a/rule_sample.js b/rule_sample.js index fb12c10..53eede7 100644 --- a/rule_sample.js +++ b/rule_sample.js @@ -6,11 +6,17 @@ var rules = { "localFile" :"", //this file will be returned to user when host and path pattern both meets the request "localDir" :"~/" //find the file of same name in localdir. anyproxy will not read localDir settings unless localFile is falsy } + // ,{ + // "host" :/./, + // "path" :/\.(png|gif|jpg|jpeg)/, + // "localFile" :"/Users/Stella/tmp/test.png", + // "localDir" :"~/" + // } ,{ "host" :/./, - "path" :/\.(png|gif|jpg|jpeg)/, - "localFile" :"/Users/Stella/tmp/test.png", - "localDir" :"~/" + "path" :/tps/, + "localFile" :"", + "localDir" :"/Users/Stella/tmp/" } ] ,"httpsConfig":{