Replies: 2 comments
-
This is just a small example. In reality, you might need to consider encoding and streaming, etc. import { Hono } from "hono"
import type { MiddlewareHandler } from "hono"
const contentSize: MiddlewareHandler = async (c, next) => {
await next()
const res = c.res.clone()
const body = await res.text()
const contentLength = Buffer.byteLength(body, "utf8")
c.res.headers.set("Content-Length", contentLength.toString())
}
const app = new Hono().use(contentSize).get("/:msg", (c) => {
const msg = c.req.param("msg")
return c.text(msg)
})
const res = await app.request("/hello")
console.log(res.headers.get("Content-Length")) // output: 5 |
Beta Was this translation helpful? Give feedback.
0 replies
-
For future reference, I ended up implementing it like this: const teeResponse = async (
response: Response,
): Promise<[Response, Response]> => {
if (!response.body) {
return [response, response];
}
const [stream1, stream2] = response.body.tee();
const newResponse1 = new Response(stream1, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
const newResponse2 = new Response(stream2, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
return [newResponse1, newResponse2];
};
const measureResponseSize = async (
response: Response,
): Promise<[number, Response]> => {
const [newResponse1, newResponse2] = await teeResponse(response);
let size = 0;
if (newResponse2.body) {
let done = false;
const reader = newResponse2.body.getReader();
while (!done) {
const result = await reader.read();
done = result.done;
if (!done && result.value) {
size += result.value.byteLength;
}
}
}
return [size, newResponse1];
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I want to implement a middleware that captures the size of the response. Most frameworks set the Content-Length header, but Hono does not seem to. How could one achieve this?
Beta Was this translation helpful? Give feedback.
All reactions