-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho.js
More file actions
90 lines (75 loc) · 2.43 KB
/
echo.js
File metadata and controls
90 lines (75 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
var http = require("http"),
fs = require("fs")
var configFileContent = fs.readFileSync("config.json","utf-8")
var echoJSConfig = eval(configFileContent)
var int = 0;
for(var key in echoJSConfig) {
var proxyConfig = echoJSConfig[key]
proxyConfig.name = key;
var proxyPort = proxyConfig.port;
var endpoint = proxyConfig.endpoint;
var echoPort = proxyConfig.echoPort;
if(proxyPort != null) {
var proxyServer = http.createServer(function(req,res) {
var fileName = getProxyFileName(key,req)
var req_options = {
host: endpoint.host,
port: endpoint.port,
path: req.url,
method: req.method
}
if(fs.existsSync(fileName))
fs.writeFileSync(fileName,"")
var proxy_req = http.request(req_options, function(proxy_response) {
proxy_response.pipe(res)
var responseCache = ''
proxy_response.on('data', function (chunk) {
fs.appendFileSync(fileName,chunk)
})
res.writeHead(proxy_response.statusCode, proxy_response.headers)
})
req.pipe(proxy_req)
});
proxyServer.listen(proxyPort)
}
if(echoPort != null) {
var echoServer = http.createServer(function(req,res) {
var fileName = getProxyFileName(proxyConfig,req);
try {
var discoveredResponseType = discoverType(proxyConfig,fileName);
if(discoveredResponseType != null)
res.setHeader("Content-Type", discoveredResponseType);
fs.readFile(fileName,function(err,response) {
if(err == null) {
var myresponse = response.toString().replace(/\s*?\/\/.*?\n/g,"")
res.end(myresponse);
}
else
res.end("could not deliver echo because of: "+err);
});
}
catch (exception) {
res.end("could not deliver echo because of: "+exception);
}
});
echoServer.listen(echoPort);
console.log("Echo Server for \""+key+"\" listining on port: "+echoPort);
}
}
function discoverType(config,fileName) {
if(config.returnTypes != null) {
for(var typeConfig in config.returnTypes) {
if(fileName.match(config.returnTypes[typeConfig].regEx) != null)
return config.returnTypes[typeConfig].type;
}
}
if(config.defaultReturnType != null)
return config.defaultReturnType;
return null;
}
function getProxyFileName(config, req) {
var directory = config.directory+"/"+config.name;
if(!fs.existsSync(directory))
fs.mkdirSync(directory)
return directory+"/"+req.url.replace(/\//g,"@@")+"_"+req.method
}