Skip to content

Commit

Permalink
feat: [BREAKING] Content-Length is not added automatically (#183)
Browse files Browse the repository at this point in the history
Close #179

Calculating Content-Length makes returning a response slowly. But Wrangler, Miniflare, or Cloudflare calculate Content-Length and add to a header automatically. So, we do not have to do it by ourselves.
  • Loading branch information
yusukebe authored Apr 27, 2022
1 parent 7cd3c70 commit 501854f
Show file tree
Hide file tree
Showing 5 changed files with 7 additions and 35 deletions.
7 changes: 0 additions & 7 deletions src/context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,6 @@ describe('Context', () => {
expect(obj['hono']).toBe('great app')
})

it('Should return `Content-Length`', async () => {
let res = c.text('abcdefg')
expect(res.headers.get('Content-Length')).toBe('7')
res = c.text('炎')
expect(res.headers.get('Content-Length')).toBe('3')
})

it('Has headers, status, and statusText', async () => {
c.header('X-Custom1', 'Message1')
c.header('X-Custom2', 'Message2')
Expand Down
13 changes: 0 additions & 13 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,21 +67,8 @@ export class Context<RequestParamKeyType = string> {
init.status = init.status || this.#status || 200
init.statusText =
init.statusText || this.#statusText || getStatusText(init.status as StatusCode)

init.headers = { ...this.#headers, ...init.headers }

// Content-Length
let length = 0
if (data) {
if (data instanceof ArrayBuffer) {
length = data.byteLength
} else if (typeof data == 'string') {
const Encoder = new TextEncoder()
length = Encoder.encode(data).byteLength || 0
}
}
init.headers = { ...init.headers, ...{ 'Content-Length': length.toString() } }

return new Response(data, init)
}

Expand Down
8 changes: 4 additions & 4 deletions src/middleware/logger/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,23 @@ describe('Logger by Middleware', () => {
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(log.startsWith(' --> GET /empty \x1b[32m200\x1b[0m')).toBe(true)
expect(log.endsWith(' 0b')).toBe(true)
expect(log).toMatch(/m?s$/)
})

it('Log status 200 with small body', async () => {
const res = await app.request('http://localhost/short')
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(log.startsWith(' --> GET /short \x1b[32m200\x1b[0m')).toBe(true)
expect(log.endsWith(` ${shortRandomString.length}b`)).toBe(true)
expect(log).toMatch(/m?s$/)
})

it('Log status 200 with big body', async () => {
const res = await app.request('http://localhost/long')
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(log.startsWith(' --> GET /long \x1b[32m200\x1b[0m')).toBe(true)
expect(log.endsWith(` ${longRandomString.length / 1024}kB`)).toBe(true)
expect(log).toMatch(/m?s$/)
})

it('Log status 404', async () => {
Expand All @@ -50,6 +50,6 @@ describe('Logger by Middleware', () => {
expect(res).not.toBeNull()
expect(res.status).toBe(404)
expect(log.startsWith(' --> GET /notfound \x1b[33m404\x1b[0m')).toBe(true)
expect(log.endsWith(` ${msg.length}b`)).toBe(true)
expect(log).toMatch(/m?s$/)
})
})
10 changes: 3 additions & 7 deletions src/middleware/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,12 @@ function log(
method: string,
path: string,
status?: number,
elapsed?: string,
contentLength?: string
elapsed?: string
) {
const out =
prefix === LogPrefix.Incoming
? ` ${prefix} ${method} ${path}`
: ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed} ${contentLength}`
: ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`
fn(out)
}

Expand All @@ -63,9 +62,6 @@ export const logger = (fn = console.log) => {

await next()

const len = parseFloat(c.res.headers.get('Content-Length'))
const contentLength = isNaN(len) ? '0' : len < 1024 ? `${len}b` : `${len / 1024}kB`

log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start), contentLength)
log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start))
}
}
4 changes: 0 additions & 4 deletions src/middleware/serve-static/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,13 @@ describe('ServeStatic Middleware', () => {
expect(res.status).toBe(200)
expect(await res.text()).toBe('This is plain.txt')
expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')
expect(res.headers.get('Content-Length')).toBe('17')
})

it('Should return hono.html', async () => {
const res = await app.request('http://localhost/static/hono.html')
expect(res.status).toBe(200)
expect(await res.text()).toBe('<h1>Hono!</h1>')
expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')
expect(res.headers.get('Content-Length')).toBe('14')
})

it('Should return 404 response', async () => {
Expand All @@ -55,14 +53,12 @@ describe('ServeStatic Middleware', () => {
expect(res.status).toBe(200)
expect(await res.text()).toBe('That is plain.txt')
expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')
expect(res.headers.get('Content-Length')).toBe('17')
})

it('Should return index.html', async () => {
const res = await app.request('http://localhost/static/top')
expect(res.status).toBe(200)
expect(await res.text()).toBe('<h1>Top</h1>')
expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')
expect(res.headers.get('Content-Length')).toBe('12')
})
})

0 comments on commit 501854f

Please sign in to comment.