0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-22 11:17:33 +01:00

fix(bun): serve static middleware returns 404 correctly (#538)

This commit is contained in:
Yusuke Wada 2022-09-19 12:25:04 +09:00 committed by GitHub
parent ac1c01df4a
commit 5573c59cf6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 12 deletions

View File

@ -67,6 +67,11 @@ describe('Serve Static Middleware', () => {
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('image/x-icon')
})
it('Should return 404 response', async () => {
const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))
expect(res.status).toBe(404)
})
})
// JWT is not available for Bun

View File

@ -1,5 +1,6 @@
// @denoify-ignore
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { existsSync } from 'fs'
import type { MiddlewareHandler } from '../../hono'
import { getFilePath } from '../../utils/filepath'
import { getMimeType } from '../../utils/mime'
@ -20,7 +21,6 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew
if (c.res && c.finalized) {
await next()
}
const url = new URL(c.req.url)
let path = getFilePath({
@ -28,20 +28,22 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew
root: options.root,
defaultDocument: DEFAULT_DOCUMENT,
})
path = `./${path}`
const content = file(path)
if (content) {
const mimeType = getMimeType(path)
if (mimeType) {
c.header('Content-Type', mimeType)
if (existsSync(path)) {
const content = file(path)
if (content) {
const mimeType = getMimeType(path)
if (mimeType) {
c.header('Content-Type', mimeType)
}
// Return Response object
return c.body(content)
}
// Return Response object
return c.body(content)
} else {
console.warn(`Static file: ${path} is not found`)
await next()
}
console.warn(`Static file: ${path} is not found`)
await next()
return
}
}