I’m stuck on Stage Persistent connection.
Here are my logs after the second request:
remote: [tester::#AG9] Failed to read response:
remote: [tester::#AG9] Received: "" (no content received)
remote: [tester::#AG9] ^ error
remote: [tester::#AG9] Error: Expected: HTTP-version, Received: ""
remote: [tester::#AG9] Test failed
remote: [tester::#AG9] Terminating program
remote: [tester::#AG9] Program terminated successfully
And here’s a snippet of my code:
socket.on("data", async (data) => {
req += data.toString();
while (req.includes("\r\n\r\n")) {
const [raw, ...rest] = req.split("\r\n\r\n");
const headers = raw.split("\r\n").reduce((acc, line) => {
const [key, value] = line.split(": ");
if (key && value) acc[key] = value;
return acc;
}, {});
const path = raw.split(" ")[1];
if (path === "/") {
socket.write("HTTP/1.1 200 OK\r\n\r\n");
} else if (path.startsWith("/files/")) {
const directory = process.argv[3];
const filename = path.split("/files/")[1];
let res;
if (raw.includes("POST")) {
const content = getBody(raw);
res = await postFileRequest(filename, content);
}
if (existsSync(`${directory}/${filename}`)) {
const content = readFileSync(`${directory}/${filename}`).toString();
const res = `HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: ${content.length}\r\n\r\n${content}\r\n`;
socket.write(res);
} else {
socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
}
} else if (path === "/user-agent") {
if (headers["User-Agent"]) {
const res = headers["User-Agent"];
socket.write(`HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: ${res.length}\r\n\r\n${res}\r\n`);
}
} else if (path.startsWith("/echo/")) {
let body = path.split("/echo/")[1];
const contentEncoding = getAcceptContent(raw);
if (contentEncoding) {
const content = gzipSync(body);
const data = new Buffer.from(content);
body = contentEncoding.includes("gzip") ? data : body;
socket.write(
`HTTP/1.1 200 OK\r\n${contentEncoding ? "Content-Encoding: " + contentEncoding : ""}\r\nContent-Type: text/plain\r\nContent-Length: ${
body.length
}\r\n\r\n`
);
socket.write(data);
}
socket.write(`HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: ${body.length}\r\n\r\n${body}\r\n\r`);
} else {
socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
}
if (headers["Connection"] && headers["Connection"].toLowerCase() === "close") {
socket.end();
}
req = rest.join("");
}
});