2022-09-13 23:17:20 +00:00
|
|
|
import type { MiddlewareHandler } from '../hono.ts'
|
2022-07-02 14:20:09 +00:00
|
|
|
import { getFilePath } from '../utils/filepath.ts'
|
|
|
|
import { getMimeType } from '../utils/mime.ts'
|
|
|
|
|
|
|
|
export type ServeStaticOptions = {
|
|
|
|
root?: string
|
|
|
|
path?: string
|
|
|
|
}
|
|
|
|
|
|
|
|
const DEFAULT_DOCUMENT = 'index.html'
|
|
|
|
|
2022-09-13 23:17:20 +00:00
|
|
|
export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {
|
|
|
|
return async (c, next): Promise<Response | undefined> => {
|
2022-07-02 14:20:09 +00:00
|
|
|
// Do nothing if Response is already set
|
2022-09-02 12:13:47 +00:00
|
|
|
if (c.finalized) {
|
2022-07-02 14:20:09 +00:00
|
|
|
await next()
|
|
|
|
}
|
|
|
|
|
|
|
|
const url = new URL(c.req.url)
|
|
|
|
|
|
|
|
let path = getFilePath({
|
|
|
|
filename: options.path ?? url.pathname,
|
|
|
|
root: options.root,
|
|
|
|
defaultDocument: DEFAULT_DOCUMENT,
|
|
|
|
})
|
|
|
|
|
|
|
|
path = `./${path}`
|
|
|
|
const content = await Deno.readFile(path)
|
|
|
|
if (content) {
|
|
|
|
const mimeType = getMimeType(path)
|
|
|
|
if (mimeType) {
|
|
|
|
c.header('Content-Type', mimeType)
|
|
|
|
}
|
|
|
|
// Return Response object
|
|
|
|
return c.body(content)
|
|
|
|
} else {
|
|
|
|
console.warn(`Static file: ${path} is not found`)
|
|
|
|
await next()
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|