-
Notifications
You must be signed in to change notification settings - Fork 4
/
proxy.js
74 lines (59 loc) · 2.17 KB
/
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
const http = require('http');
const url = require('url');
const { blockResources } = require('./middleware');
const { imageExists, cssExists } = require('./plugins');
const { logger } = require('./util');
const parseIncomingRequest = (clientRequest, clientResponse) => {
const requestToFulfil = url.parse(clientRequest.url);
// Frame the request to be forwarded via Backend to External Source
const options = {
method: clientRequest.method,
headers: clientRequest.headers,
host: requestToFulfil.hostname,
port: requestToFulfil.port || 80,
path: requestToFulfil.path
}
// PLUGINS
if (blockResources(options, imageExists)) {
options.allowed = false;
logger(options);
// Don't allow the request to proceed and terminate here itself
clientResponse.end();
} else {
options.allowed = true;
logger(options);
// Execute the Request
executeRequest(options, clientRequest, clientResponse);
}
}
const executeRequest = (options, clientRequest, clientResponse) => {
const externalRequest = http.request(options, (externalResponse) => {
// Write Headers to clientResponse
clientResponse.writeHead(externalResponse.statusCode, externalResponse.headers);
// Forward the data being received from external source back to client
externalResponse.on("data", (chunk) => {
clientResponse.write(chunk);
});
// End the client response when the request from external source has completed
externalResponse.on("end", () => {
clientResponse.end();
});
});
// Map data coming from client request to the external request being made
clientRequest.on("data", (chunk) => {
if(JSON.parse(chunk.toString()).language === "english") {
chunk = Buffer.from(JSON.stringify({"language":"spanish"}))
}
externalRequest.write(chunk);
});
// Map the end of client request to the external request being made
clientRequest.on("end", () => {
externalRequest.end();
});
}
// Create a HTTP server
const server = http.createServer(parseIncomingRequest);
// Listen to PORT 4998
server.listen(4998, () => {
console.log("******************* PROXY STARTED ON http://localhost:4998 *******************\n")
});