Skip to content
Open
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
10 changes: 5 additions & 5 deletions lib/httpParser.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
const { findFirstBrac, HTTPbody, JSONbodyParser, queryParser } = require('./utils.js')

// Async function to parse the HTTP request
async function httpParser(request, connection = {}) {
async function httpParser (request, connection = {}) {
try {
const req = {} // Create a new object to store the parsed request
const requestString = request.toString() // Convert buffer to string, if necessary

// Set client IP address (similar to Express)
req.ip = connection.remoteAddress || '127.0.0.1'

// Step 1: Split the request into headers and body by finding "\r\n\r\n"
const headerBodySplit = requestString.split('\r\n\r\n') // Headers and body are separated by double newline
if (headerBodySplit.length < 1) {
throw new Error('Invalid HTTP request format')
}

const headersPart = headerBodySplit[0] // First part is the headers
const bodyPart = headerBodySplit[1] || '' // Second part is the body, default to empty string if no body

Expand All @@ -38,7 +38,7 @@ async function httpParser(request, connection = {}) {
if (line) {
const colonIndex = line.indexOf(':')
if (colonIndex === -1) continue // Skip malformed headers

const key = line.slice(0, colonIndex).trim().toLowerCase()
const value = line.slice(colonIndex + 1).trim()
req.headers[key] = value
Expand Down Expand Up @@ -69,7 +69,7 @@ async function httpParser(request, connection = {}) {
req.body = {}
// Store CORS-specific headers for easy access
req.cors = {
origin: req.headers['origin'],
origin: req.headers.origin,
method: req.headers['access-control-request-method'],
headers: req.headers['access-control-request-headers']
}
Expand Down
Loading