Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(serve-static): add onFound option #198

Merged
merged 1 commit into from
Sep 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,22 @@ app.use(
)
```

#### `onFound`

You can specify handling when the requested file is found with `onFound`.

```ts
app.get(
'/static/*',
serveStatic({
// ...
onFound: (_path, c) => {
c.header('Cache-Control', `public, immutable, max-age=31536000`)
},
})
)
```

#### `onNotFound`

The `onNotFound` is useful for debugging. You can write a handle for when a file is not found.
Expand Down
8 changes: 5 additions & 3 deletions src/serve-static.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import type { Context, MiddlewareHandler } from 'hono'
import type { Context, Env, MiddlewareHandler } from 'hono'
import { getFilePath, getFilePathWithoutDefaultDocument } from 'hono/utils/filepath'
import { getMimeType } from 'hono/utils/mime'
import { createReadStream, lstatSync } from 'fs'
import type { ReadStream, Stats } from 'fs'

export type ServeStaticOptions = {
export type ServeStaticOptions<E extends Env = Env> = {
/**
* Root path, relative to current working directory from which the app was started. Absolute paths are not supported.
*/
root?: string
path?: string
index?: string // default is 'index.html'
rewriteRequestPath?: (path: string) => string
onNotFound?: (path: string, c: Context) => void | Promise<void>
onFound?: (path: string, c: Context<E>) => void | Promise<void>
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>
}

const createStreamBody = (stream: ReadStream) => {
Expand Down Expand Up @@ -87,6 +88,7 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew
await options.onNotFound?.(path, c)
return next()
}
await options.onFound?.(path, c)

const mimeType = getMimeType(path)
if (mimeType) {
Expand Down
11 changes: 10 additions & 1 deletion test/serve-static.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,15 @@ import { createAdaptorServer } from './../src/server'
describe('Serve Static Middleware', () => {
const app = new Hono()

app.use('/static/*', serveStatic({ root: './test/assets' }))
app.use(
'/static/*',
serveStatic({
root: './test/assets',
onFound: (path, c) => {
c.header('X-Custom', `Found the file at ${path}`)
},
})
)
app.use('/favicon.ico', serveStatic({ path: './test/assets/favicon.ico' }))
app.use(
'/dot-static/*',
Expand Down Expand Up @@ -34,6 +42,7 @@ describe('Serve Static Middleware', () => {
expect(res.status).toBe(200)
expect(res.text).toBe('<h1>Hello Hono</h1>')
expect(res.headers['content-type']).toBe('text/html; charset=utf-8')
expect(res.headers['x-custom']).toBe('Found the file at ./test/assets/static/index.html')
})

it('Should return hono.html', async () => {
Expand Down
Loading