-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstatic-proxy.js
202 lines (166 loc) · 5.43 KB
/
static-proxy.js
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
var http = require('http'),
fs = require('fs'),
path = require('path'),
url = require('url'),
qs = require('querystring'),
extend = function(d, s){
for(var prop in s){
d[prop] = s[prop]
}
return d;
};
var checkAndDo = function(value, obj, doThis, request, response){
for(var regStr in obj){
var reg = new RegExp(regStr);
if(reg.test(value)){
return doThis(regStr, obj[regStr], request, response);
}
}
},
fakeReload = function(filename, cb){
fs.readFile( path.join( __dirname, filename ), function(error, content) {
//console.log("(function(exports){ "+content+"; return exports })({})")
cb( eval("(function(exports){ "+content+"; return exports })({})") );
});
},
sendToProxy = function(requestUrl, redirectTo, request, response){
var proxyurl = request.url.replace(requestUrl, redirectTo),
parsed = url.parse(proxyurl, true);
// make a request
var proxy_request = http.request({
hostname: parsed.hostname,
port: parsed.port || 80,
path: parsed.path,
method: request.method || "GET",
headers: request.headers
});
console.log(" ",request.method, request.url, "->",proxyurl)
// REQUEST -> PROXY
request.on('data', function(chunk) {
proxy_request.write(chunk, 'binary');
});
request.on('end', function() {
proxy_request.end();
});
// PROXY -> RESPONSE
proxy_request.on('response', function (proxy_response) {
proxy_response.on('data', function(chunk) {
response.write(chunk, 'binary');
});
proxy_response.on('end', function() {
response.end();
});
response.writeHead(proxy_response.statusCode, proxy_response.headers);
});
proxy_request.on("error", function(e){
response.writeHead(500, { 'Content-Type': "text/html" });
response.end("<html><body>"+e+"</body></html>", 'utf-8');
})
return true;
},
handleSpecial = function(requestUrl, specialFunction, request, response){
var matching = request.method.toUpperCase() + " "+ request.url;
var body = '',
reg = new RegExp(requestUrl);
// get all data from server
request.on('data', function (chunk) {
body+= chunk;
});
request.on('end', function(){
// after we have all data
var parts = matching.match(reg);
// break up the form params into an object
parts.unshift(qs.parse(body));
var data = specialFunction.apply(url.parse(request.url, true), parts);
response.writeHead(200, { 'Content-Type': "application/json" });
response.end( JSON.stringify(data), 'utf-8');
})
return true;
},
serverCode = function (request, response) {
var parsedUrl = url.parse(request.url, true);
// PROXY CHECK
if( checkAndDo(request.url, config.proxies || {}, sendToProxy, request, response) ) {
return;
}
if(checkAndDo(request.method.toUpperCase() + " "+ request.url, config.special || {}, handleSpecial, request, response)){
return;
}
console.log('->', request.method, request.url);
var basePath = path.dirname( path.join( __dirname, current ) );
var filePath = path.join( basePath, config.root, parsedUrl.pathname );
if (filePath == './') {
filePath = './index.htm';
}
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.webm':
contentType = 'video/webm';
break;
case '.ogg':
contentType = 'audio/ogg'
break;
}
fs.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
//setTimeout(function(){
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
//},parseInt(Math.random()*1000))
}
});
}
else {
response.writeHead(404);
response.end();
}
});
},
config,
server,
setConfig = function(){
// save config settings
var old = extend({}, config||{});
fakeReload(current, function(c){
config = c;
console.log("Reading "+current)
//for(var prop in config){
// console.log(" "+prop)
//}
if(!server){
server = http.createServer(serverCode).listen(config.port);
console.log('Server running at http://127.0.0.1:'+config.port+'/');
} else if(config.port != old.port){
console.log("Restarting Server")
server.close(function(){
server.listen(config.port);
console.log('Server running at http://127.0.0.1:'+config.port+'/');
})
}
});
};
// FIND static-proxy-config.js
// check within current folder, then check parent, then check
var current = "static-proxy-config.js";
for(var i =0; i < 4; i++){
if( fs.existsSync( path.join(__dirname, current) ) ){
fs.watch(path.join(__dirname, current),{persistent: false}, setConfig);
setConfig();
break;
} else {
current = "../"+current;
}
}