node-http-proxy/index.js

104 lines
2.5 KiB
JavaScript
Raw Normal View History

2019-01-25 00:54:48 +00:00
var net = require('net');
2019-01-25 03:07:42 +00:00
var http = require('http');
var fs = require('fs');
var winston = require("winston");
const logger = winston.createLogger({
transports: [
new winston.transports.File({filename: 'proxy.log'})
]
});
2019-01-25 03:07:42 +00:00
class HttpRequest {
constructor(attrs) {
2019-01-25 03:20:17 +00:00
this.attrs = attrs;
this.logSomething = this.logSomething.bind(this);
this.forwardRequest = this.forwardRequest.bind(this);
}
// TODO - not working yet. will come back to this.
logSomething() {
logger.log({
level: 'info',
message: this.attrs
})
2019-01-25 03:07:42 +00:00
}
async forwardRequest() {
// TODO - rebuild the request and return it to the client.
}
2019-01-25 03:07:42 +00:00
}
/**
* Parse an HTTP request.
* @param {String} bytes
*/
async function parseHttpRequest(bytes) {
let httpRequestAttrs = {headers: {}};
2019-01-25 03:07:42 +00:00
bytes.split("\r\n").map((row) => {
// Match against HTTP verbs from the first row.
if (row.match('GET|POST|PUT|PATCH|UPDATE|DELETE')) {
console.log("FIRST ROW");
console.log(row);
let typeInfo = row.split(" ");
if (typeInfo.length !== 3) {
console.log("Bad HTTP request");
return null;
}
httpRequestAttrs["Method"] = typeInfo[0];
httpRequestAttrs["Path"] = typeInfo[1];
httpRequestAttrs["HttpVersion"] = typeInfo[2];
2019-01-25 03:07:42 +00:00
} else {
let currentRow = row.split(":");
console.log(currentRow);
if (currentRow[0] !== '')
httpRequestAttrs.headers[currentRow[0]] = currentRow[1].trim();
2019-01-25 03:07:42 +00:00
}
2019-01-25 03:20:17 +00:00
});
return new HttpRequest(httpRequestAttrs);
2019-01-25 03:07:42 +00:00
}
2019-01-25 00:54:48 +00:00
2019-01-25 01:43:49 +00:00
/**
* Log the request and forward it.
* @param {String} bytes
*/
2019-01-25 00:54:48 +00:00
async function logAndSend(bytes) {
2019-01-25 01:43:49 +00:00
console.log(bytes)
2019-01-25 00:54:48 +00:00
}
function startServer() {
var server = net.createServer((socket) => {
socket.on('end', (c) => {
console.log("Client disconnected");
});
socket.on("data", (c) => {
parseHttpRequest(c.toString())
.then((req) => {
req.logSomething();
return req;
})
.then((req) => {
})
});
})
server.on('connection', (c) => {
console.log("Client connected!");
});
2019-01-25 00:54:48 +00:00
server.listen(8124, () => {
console.log("Server bound.");
});
2019-01-25 01:43:49 +00:00
return server;
}
2019-01-25 03:13:48 +00:00
startServer();
module.exports = [parseHttpRequest];