2022-09-27 12:40:37 +00:00
|
|
|
import type { Context } from '../context.ts'
|
2022-10-31 15:07:56 +00:00
|
|
|
import type { Next } from '../types.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-27 12:40:37 +00:00
|
|
|
export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {
|
|
|
|
return async (c: Context, next: Next) => {
|
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()
|
2022-10-09 15:11:36 +00:00
|
|
|
return
|
2022-07-02 14:20:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const url = new URL(c.req.url)
|
|
|
|
|
|
|
|
let path = getFilePath({
|
|
|
|
filename: options.path ?? url.pathname,
|
|
|
|
root: options.root,
|
|
|
|
defaultDocument: DEFAULT_DOCUMENT,
|
|
|
|
})
|
|
|
|
|
|
|
|
path = `./${path}`
|
2022-09-19 03:22:55 +00:00
|
|
|
|
|
|
|
let content
|
|
|
|
|
|
|
|
try {
|
|
|
|
content = await Deno.readFile(path)
|
|
|
|
} catch (e) {
|
|
|
|
console.warn(`${e}`)
|
|
|
|
}
|
|
|
|
|
2022-07-02 14:20:09 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|