Skip to content

Commit fc9f9ab

Browse files
zwpaperyusukebe
andauthored
fix: better handle range parse to avoid NaN error (#276)
* fix: better handle range parse to avoid NaN error * fix the format error and add a test * remove unnecessary comment * remove the unnecessary logic --------- Co-authored-by: Yusuke Wada <[email protected]>
1 parent 660e784 commit fc9f9ab

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

src/serve-static.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,8 @@ export const serveStatic = <E extends Env = any>(
149149
c.header('Date', stats.birthtime.toUTCString())
150150

151151
const parts = range.replace(/bytes=/, '').split('-', 2)
152-
const start = parts[0] ? parseInt(parts[0], 10) : 0
153-
let end = parts[1] ? parseInt(parts[1], 10) : stats.size - 1
152+
const start = parseInt(parts[0], 10) || 0
153+
let end = parseInt(parts[1], 10) || size - 1
154154
if (size < end - start + 1) {
155155
end = size - 1
156156
}

test/serve-static.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,13 @@ describe('Serve Static Middleware', () => {
166166
expect(res.text).toBe('This is plain.txt')
167167
})
168168

169+
it('Should handle invalid range header gracefully without NaN error', async () => {
170+
const res = await request(server).get('/static/plain.txt').set('range', 'hello')
171+
expect(res.status).toBe(206)
172+
expect(res.headers['content-length']).toBe('17')
173+
expect(res.headers['content-range']).toBe('bytes 0-16/17')
174+
})
175+
169176
it('Should handle the `onNotFound` option', async () => {
170177
const res = await request(server).get('/on-not-found/foo.txt')
171178
expect(res.status).toBe(404)

0 commit comments

Comments
 (0)