jkyberneees / low-http-server

HTTP Server implementation in top of uWebSocket.js
MIT License
50 stars 7 forks source link

Incorrect Status Code When Request is Piped #25

Open nicosefer opened 1 year ago

nicosefer commented 1 year ago

Issue Description

Current Behavior

The statusCode is not correctly set when the request is piped. The writeHead method sets the statusCode internally, but when the request is piped, the statusCode is not updated in the response.

Expected Behavior

The statusCode should be correctly set in the response when the request is piped, reflecting the value set using the writeHead method.

Steps to Reproduce

  1. Create a server using low-http-server.
  2. Set the statusCode using the writeHead method.
  3. Pipe a request to the server.
  4. Inspect the statusCode in the response.

Code Example

import cero from "0http";
import low from "low-http-server";
import http from "http";

const { router, server } = cero({
  server: low(),
  cacheSize: 0,
});

server.listen(3000, (socket) => {
  console.log(`server started`);
});

function handleRequest(
  req,
  res,
) {
  const { headers, method, originalUrl, body } = req;
  const host = headers.host;
  const forwardReq = http
    .request(
      {
        host: host,
        path: originalUrl,
        headers: headers,
        method: method,
      },
      (newRes) => {
        const headers = newRes.headers;
        res.writeHead(newRes.statusCode, headers);
        newRes.pipe(res);
      }
    )
  req.pipe(forwardReq);
}

router.delete("/*", handleRequest);

Solution Proposal

I have identified a potential solution to address the issue. In the HttpResponse class of the low-http-server library, within the writeAllHeaders method, I suggest making the following modification:

this.on('pipe', (_) => {
  if (this.finished) return
  this.res.writeStatus(`${this.statusCode.toString()} ${this.statusMessage}`)
  this.writeAllHeaders()
})

Additional Information