Removing unnecessary parsing from code, prefer piping directly

This commit is contained in:
Jacob Windle 2019-01-26 11:09:39 -05:00
parent 89bd9f9005
commit 8612ee9ee4

108
index.js
View File

@ -12,104 +12,24 @@ const logger = winston.createLogger({
] ]
}); });
/**
* HttpRequest class,
*
* Encapsulates logging a request.
*
* TODO - Enable request forwarding here.
*/
class HttpRequest {
constructor(attrs) {
this.attrs = attrs;
this.logSomething = this.logSomething.bind(this);
this.forwardRequest = this.forwardRequest.bind(this);
}
/**
* Using Winston, log the request.
*/
logSomething() {
logger.log({
level: 'info',
message: this.attrs
})
}
/**
* Forward the request, returning a promise for the result.
*
* TODO - Implement me.
*/
forwardRequest(callbackFn) {
console.log("Forwarding.")
http.request({
host: this.attrs.headers.Host,
method: this.attrs.Method,
headers: this.attrs.headers
}, callbackFn);
}
}
/**
* Parse an HTTP request.
* @param {String} bytes
*/
async function parseHttpRequest(bytes) {
// Object to eventually save in HttpRequest class.
let httpRequestAttrs = {headers: {}};
// Parse request row by row.
bytes.split("\r\n").map((row) => {
// Match against HTTP verbs from the first row.
if (row.match('GET|POST|PUT|PATCH|UPDATE|DELETE')) {
let typeInfo = row.split(" ");
// Malformed if there aren't at least 3 items here.
if (typeInfo.length !== 3) {
console.log("Bad HTTP request");
return null;
}
httpRequestAttrs["Method"] = typeInfo[0];
httpRequestAttrs["Path"] = typeInfo[1];
httpRequestAttrs["HttpVersion"] = typeInfo[2];
} else {
// Headers, parse accordingly
let currentRow = row.split(":");
if (currentRow[0] !== '')
httpRequestAttrs.headers[currentRow[0]] = currentRow[1].trim();
}
});
return new HttpRequest(httpRequestAttrs);
}
function startServer() { function startServer() {
// Start the server, set up data and end handlers. // Start the server, set up data and end handlers.
var server = net.createServer((socket) => { var server = http.createServer();
socket.on('end', (c) => { server.on('request', (request, response) => {
console.log("Client disconnected"); let body = [];
}); // Use closure for request.
socket.on("data", (c) => { let req = request;
// Parse HTTP Request returns promise for HttpRequest (async). let res = response;
// Log it and pass that along.
parseHttpRequest(c.toString())
.then((req) => {
req.logSomething();
req.forwardRequest((res) => {
console.log("Received response");
console.log(res);
});
})
});
})
// Connection handler (currently unused). request.on("data", (chunk) => {
server.on('connection', (c) => { body.push(chunk);
console.log("Client connected!"); }).on("end", () => {
}); body = Buffer.concat(body).toString();
logger.info({message: "Got a message!"});
logger.info({message: req});
})
})
// Start the server // Start the server
server.listen(8124, () => { server.listen(8124, () => {