-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
executable file
·222 lines (171 loc) · 7.96 KB
/
Copy pathapp.js
File metadata and controls
executable file
·222 lines (171 loc) · 7.96 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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/*global require*/
(function () {
"use strict";
// Load dependencies
var http = require('http');
var fs = require('fs');
var util = require('util');
var config = require('./config.json');
// Setup globals
var scope = this;
var cacheBase = config.cacheBase || '';
var remoteServer = config.remoteServer || '';
var serverPort = config.serverPort || 80;
function processUrl(url) {
if (url.indexOf('?') > 0) {
var urlParts = url.split('?');
var queryParts = urlParts[1].split('&');
var requestUri = urlParts[0];
var queryString = {};
for (var t = 0; t < queryParts.length; t++) {
var parts = queryParts[t].split('=');
queryString[parts[0]] = parts[1];
}
return { requestUri: requestUri, queryString: queryString };
} else {
return { requestUri: url, queryString: {} };
}
}
function checkSubdirectory(path) {
var exists = fs.existsSync(path);
if (exists === true) {
console.log('Checking for subdirectory: ' + path + ' [FOUND]');
} else {
console.log('Checking for subdirectory: ' + path + ' [NOT FOUND]. Creating...');
fs.mkdir(path, '0777');
}
return;
}
function retrieveFromCache(cachePath, callback) {
console.log('Retrieving from cache: ' + cachePath);
var htmlContent = '';
callback = callback || function () { return false; };
htmlContent += fs.readFileSync(cachePath);
callback.call(scope, htmlContent);
}
function retrieveFromRemote(requestHost, requestPath, basePath, refParts, requestMethod, postContent, cachePath, callback) {
console.log('Retrieving from remote server: ' + requestPath);
var htmlContent = '';
requestMethod = requestMethod || 'GET';
callback = callback || function () { return false; };
var requestOptions = {
hostname: 'int.' + requestHost,
port: 80,
path: requestPath,
method: requestMethod
};
if (requestMethod === 'POST') {
requestOptions.headers = {
"content-type": "application/x-www-form-urlencoded",
"content-length": postContent.length.toString()
};
}
var req = http.request(requestOptions, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
htmlContent += chunk;
});
res.on('end', function () {
//check if cache folder exists
checkSubdirectory(basePath);
//create directories for each layer of reference
var incrementPath = basePath;
for (var v = 1; v < (refParts.length - 1); v++) {
incrementPath = incrementPath + '/' + refParts[v];
checkSubdirectory(incrementPath);
}
if (typeof cachePath !== 'undefined' && cachePath !== null) {
var _this = this;
console.log('Saving into cache: ' + cachePath);
fs.writeFile(cachePath, htmlContent, function (err) {
console.log('File saved');
callback.call(_this, true, htmlContent);
});
} else {
console.log('Not being cached - returning content');
callback.call(this, true, htmlContent);
}
});
});
req.on('error', function (e) {
console.log('Problem with request: ' + e.message);
callback.call(this, false, htmlContent);
});
if (requestMethod === 'POST') {
console.log('Writing post content: ' + postContent);
req.write(postContent);
}
req.end();
}
function init() {
var server = http.createServer(function (request, response) {
var postContent = '';
request.on('data', function (chunk) {
postContent += chunk.toString();
});
request.on('end', function () {
// Process URL and query params into suitable object
var urlObj = processUrl(request.url);
var requestUrl = request.url;
var refParts = [];
// Request URL cleansing to stop 301 response
if (requestUrl.substr(-1, 1) === '/') {
requestUrl = requestUrl.substr(0, (requestUrl.length - 1));
}
// Base path for vhost
var serverName = request.headers['x-forwarded-host'].replace(/[^\.]+\./, '');
var basePath = cacheBase.replace('{server_name}', serverName);
var requestPath = remoteServer.replace('{server_name}', serverName) + requestUrl;
console.log('Request recieved: ' + requestPath + ' (' + request.method + ')');
console.log('Request ref: ' + urlObj.queryString.ref);
if (typeof urlObj.queryString.ref === 'undefined') {
console.log('No REF parameter found - retrieving from remote: ' + requestPath);
retrieveFromRemote(serverName, requestUrl, basePath, refParts, request.method, postContent, null, function (result, htmlContent) {
if (result !== false) {
console.log('Writing out content length of ' + htmlContent.length);
response.writeHead(200, { "Content-Type": "text/html" });
response.end(htmlContent);
}
});
} else {
// Ref cleansing
if (urlObj.queryString.ref.indexOf('/') === 0) {
urlObj.queryString.ref = urlObj.queryString.ref.replace('/', '');
}
if (urlObj.queryString.ref.substr(-1, 1) === '/') {
urlObj.queryString.ref = urlObj.queryString.ref.substr(0, (urlObj.queryString.ref.length - 1));
}
refParts = urlObj.queryString.ref.split('/');
var cachePath = basePath;
for (var v = 1; v < refParts.length; v++) {
cachePath += '/' + refParts[v];
}
console.log('cachePath: ' + cachePath);
fs.exists(cachePath, function (exists) {
if (exists) {
console.log('File exists get from cache');
retrieveFromCache(cachePath, function (htmlContent) {
console.log('Writing out content length of ' + htmlContent.length);
response.writeHead(200, { "Content-Type": "text/html" });
response.end(htmlContent);
});
} else {
console.log('File does NOT exist get from remote');
retrieveFromRemote(serverName, requestUrl, basePath, refParts, request.method, postContent, cachePath, function (result, htmlContent) {
if (result !== false) {
console.log('Writing out content length of ' + htmlContent.length);
response.writeHead(200, { "Content-Type": "text/html" });
response.end(htmlContent);
}
});
}
});
}
});
});
// Listen on port defined in config, IP defaults to 127.0.0.1
server.listen(serverPort);
console.log('Server running at http://127.0.0.1:' + serverPort + '/');
}
init();
})();