kolodziejczak-sz / uwebsocket-serve

Static file serving for uWebSockets.js
17 stars 8 forks source link

How about Content-Encoding #3

Open Wyzix33 opened 3 years ago

Wyzix33 commented 3 years ago

This can be an enhancement, you can get the 'accept-encoding' and encode the readStream using zlib based on contentType, I've done something like this in my project:

let acceptEncoding = req.getHeader("accept-encoding");
res.cork(() => {
// add some security headers like Content-Security-Policy ... 
  if (
    !acceptEncoding ||
    contentType === "image/jpg" ||
    contentType === "image/png" ||
    contentType === "image/gif" ||
    contentType === "application/zip"
  ) {
    acceptEncoding = ""; // no encoding needed
    // add some headers res.writeHeader like Cache-Control: 'public, max-age=604800, immutable' for this kind of resources
  } else {
   // add some no-store, no-cache headers maybe and encode for other files
    if (/\bgzip\b/.test(acceptEncoding)) {
      res.writeHeader("Content-Encoding", "gzip");
      readStream = zlib.gzipSync(readStream);
    } else if (/\bdeflate\b/.test(acceptEncoding)) {
      res.writeHeader("Content-Encoding", "deflate");
      readStream = zlib.deflateSync(readStream);
    }
  }
  res.end(readStream);
});

Good job with the library, I've searched for something like this and had to do it myself for a past project...

kolodziejczak-sz commented 3 years ago

hello! yeah, current implementation lacks a lot. I think the best option would be to provide some hooks to let the devs customize the response details by themselves - this way the library will stay simple and powerful. Would you be willing to introduce such feature and submit a PR?