Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
257 changes: 101 additions & 156 deletions lib/parser.js
Original file line number Diff line number Diff line change
@@ -1,181 +1,126 @@
const request = require('../test/test.js')
const net = require('net')
const net = require("net");
const testRequest = require("../test/test.js");

// net.createServer((socket)=>{
// socket.on('data',(data)=>{
// console.log(data)
// const buff = data.toString()
// console.log(buff)
// httpParser(buff)
// })
// }).listen(8080,()=>{
// console.log("server started")
//
// })

function findFirstBrac (req, target) {
// Helper function to find the position of the first occurrence of a target character
function findFirstBrac(req, target) {
for (let i = 0; i < req.length; i++) {
if (req[i] === target) {
return i // Return the position of the target character
if (req[i] === target) {
return i; // Return the position of the target character
}
}
return -1
return -1; // Return -1 if target character is not found
}

// POST /api/users HTTP/1.1
async function httpParser (request) {
const req = new Object()
const requestString = request.split('\n')
const pos = findFirstBrac(requestString, '{')
const requestWoBody = requestString.slice(0, pos)
// console.log(requestWoBody)
req.method = requestWoBody[0].split(' ')[0]
req.path = requestString[0].split(' ')[1]
req.version = requestString[0].split(' ')[2]
if (req.method == 'GET') {
return req
}
HTTPbody(requestString, pos)
.then((data) => {
req.body = JSONbodyParser(data)
})

// console.log(requestString)
// console.log(req)
return req
}
// httpParser("POST /api/users HTTP/1.1 \nhost:www.google.com")
// console.time('Execution Time');
// JSONbodyParser("{key:value,loda:lassan,}")
// console.time()
httpParser(request).then((data) => {

})

function storePair (req, httpJSON) {
let key = ''
let i = 0
while (req[i] != ':') {
key += req[i]
req.shift()
// console.log(req)
}
req.shift()
let value = ''
i = 0
// console.log(req)
while (req[i] != ',') {
if (req[i] == null) {
break
// Parse HTTP body (handles asynchronous parsing and rejects on error)
async function HTTPbody(req, pos) {
let body = "";
return new Promise((resolve, reject) => {
let flag = 0;
try {
for (let i = pos; i < req.length; i++) {
if (req[i] === "{") {
flag++;
} else if (req[i] === "}") {
flag--;
}
body += req[i];
if (flag === 0 && req[i] === "}") break; // Stop once the body has been fully captured
}
resolve(body.replace(/\s+/g, "").replace(/"/g, "")); // Clean up the body
} catch (error) {
reject(`Error parsing HTTP body: ${error.message}`);
}
value += req[i]
req.shift()
// console.log(req)
}
req.shift()
httpJSON[key] = value
// console.log(req)
// console.log("length"+req.length)
return req
});
}

function JSONbodyParser (body) {
const req = body.split('')
const httpJSON = new Object()
let flag = 0
let pos = 0
while (req.length != 0) {
if (req[0] == '{') {
flag += 1
pos += 1
req.shift()
} else if (req[0] == '}') {
flag -= 1
pos += 1
req.shift()
// Parse JSON body
function JSONbodyParser(body) {
const req = body.split("");
const httpJSON = {};
while (req.length !== 0) {
if (req[0] === "{" || req[0] === "}") {
req.shift(); // Skip braces
} else {
// console.log(req)
storePair(req, httpJSON)
// console.log("i")
storePair(req, httpJSON); // Store key-value pair
}
}
return httpJSON;
}

// console.log(JSON.stringify(httpJSON))
// console.timeEnd('Execution Time');
return httpJSON
// Store a key-value pair from the request into the httpJSON object
function storePair(req, httpJSON) {
let key = "";
while (req[0] !== ":") {
key += req.shift(); // Collect characters until colon
}
req.shift(); // Skip the colon
let value = "";
while (req[0] !== "," && req[0] !== "}") {
value += req.shift(); // Collect value until comma or closing brace
}
if (req[0] === ",") req.shift(); // Skip the comma
httpJSON[key] = value; // Store key-value pair in JSON object
}

function HTTPbody (req, pos) {
flag = 0
let body = ''
return new Promise((resolve, reject) => {
const position = pos
for (let i = position; i < req.length; i++) {
if (req[i] == '{') {
flag++
body += req[i]
} else if (req[i] == '}') {
flag--
body += req[i]
}
body += req[i]
// Function to parse HTTP request headers and body
async function HTTPbody(req, pos) {
let body = "";
let flag = 0;

for (let i = pos; i < req.length; i++) {
if (req[i] === "{") {
flag++;
} else if (req[i] === "}") {
flag--;
}
// console.log((body.replace(/\s+/g, '').replace(/"/g, ''))) remove all white spaces and quotes
body += req[i];

resolve(body.replace(/\s+/g, '').replace(/"/g, ''))
})
}
// Simulating an asynchronous operation with a delay for demonstration purposes
await new Promise((resolve) => setTimeout(resolve, 0)); // This simulates yielding control, allowing for asynchronous flow

function queryParser (request) {
const req = new Object()
const pos = findFirstBrac(request, '?')
const query = request.slice(0, pos)
while (req.length != 0) {
storeQuery(query)
if (flag === 0 && req[i] === "}") break; // Stop once the body has been fully captured
}
}

function storeQuery (query) {
const req = query.split('')
const httpQueryJSON = new Object()
let flag = 0
let pos = 0
while (req.length != 0) {
if (req[0] == '{') {
flag += 1
pos += 1
req.shift()
} else if (req[0] == '}') {
flag -= 1
pos += 1
req.shift()
} else {
queryStorePair(req)
}
}
return httpQueryJSON
// Return cleaned-up body after parsing
return body.replace(/\s+/g, "").replace(/"/g, ""); // Clean up the body
}

function queryStorePair (req) {
let key = ''
let i = 0
while (req[i] != '=') {
key += req[i]
req.shift()
}
req.shift()
let value = ''
i = 0
while (req[i] != '&') {
value += req[i]
req.shift()
}
req.shift()
httpQueryJSON[key] = value
// Query parsing function (parses query parameters from URL)
function queryParser(url) {
const req = {};
const pos = findFirstBrac(url, "?");
if (pos === -1) return req; // Return empty object if no query parameters

const queryString = url.slice(pos + 1); // Slice starting after '?'
const queryParams = queryString.split("&");

// console.log(req)
return httpQueryJSON
queryParams.forEach((param) => {
const [key, value] = param.split("=");
req[key] = value || ""; // Store key-value pair, handle empty values
});

return req;
}

// storeQuery("key=value&loda=lassan")
queryParser('https//:fhdfjdh.com?key=value&loda=lassan')
// Example server using net module
net
.createServer((socket) => {
socket.on("data", (data) => {
const rawData = data.toString();
httpParser(rawData)
.then((parsedRequest) => {
// Example of parsed request, uncomment to log it
// console.log(parsedRequest);
})
.catch((err) => {
console.error("Error while parsing request:", err);
});
});
})
.listen(8080, () => {
// Example of server startup message, uncomment to log it
// console.log("Server started on port 8080");
});

// Example test case, uncomment to test query parsing
// console.log(queryParser("https://example.com?key=value&foo=bar"));
Loading