mirror of
https://github.com/alibaba/anyproxy.git
synced 2025-04-23 20:31:25 +00:00
update local rule
This commit is contained in:
parent
c6c2355d17
commit
3104ee167c
@ -1,53 +1,25 @@
|
|||||||
//replace all the images with local one
|
//replace all the images with local one
|
||||||
|
|
||||||
var url = require("url"),
|
var url = require("url"),
|
||||||
path = require("path"),
|
path = require("path"),
|
||||||
fs = require("fs"),
|
fs = require("fs");
|
||||||
buffer = require("buffer");
|
|
||||||
|
|
||||||
var map = [
|
var LOCAL_IMAGE = "/Users/path/to/image.png";
|
||||||
{
|
|
||||||
"host" :/./,
|
|
||||||
"path" :/\.(png|gif|jpg|jpeg)/,
|
|
||||||
"localFile" :"/Users/Stella/tmp/test.png",
|
|
||||||
"localDir" :"~/"
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
|
||||||
|
//mark if use local response
|
||||||
shouldUseLocalResponse : function(req,reqBody){
|
shouldUseLocalResponse : function(req,reqBody){
|
||||||
var host = req.headers.host,
|
if(/\.(png|gif|jpg|jpeg)$/.test(req.url)){
|
||||||
urlPattern = url.parse(req.url),
|
req.replaceLocalFile = true;
|
||||||
path = urlPattern.path;
|
|
||||||
|
|
||||||
for(var index in map){
|
|
||||||
var rule = map[index];
|
|
||||||
|
|
||||||
var hostTest = new RegExp(rule.host).test(host),
|
|
||||||
pathTest = new RegExp(rule.path).test(path);
|
|
||||||
|
|
||||||
if(hostTest && pathTest && (rule.localFile || rule.localDir) ){
|
|
||||||
var targetLocalfile = rule.localFile;
|
|
||||||
|
|
||||||
//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);
|
|
||||||
}
|
|
||||||
|
|
||||||
if(fs.existsSync(targetLocalfile)){
|
|
||||||
console.log("==>local file: " + targetLocalfile);
|
|
||||||
req.replaceLocalFile = targetLocalfile; //add a flag to req object
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}else{
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
dealLocalResponse : function(req,reqBody,callback){
|
dealLocalResponse : function(req,reqBody,callback){
|
||||||
if(req.replaceLocalFile){
|
if(req.replaceLocalFile){
|
||||||
callback(200, {"content-type":"image/png"}, fs.readFileSync(req.replaceLocalFile) );
|
callback(200, {"content-type":"image/png"}, fs.readFileSync(LOCAL_IMAGE) );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
Loading…
x
Reference in New Issue
Block a user