feat: serve static middleware (Cloudflare only) (#76)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent 223429f · Browse files · 19 files·+268 added−71 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
19 files+268 added−71 removed
- tests:+87 added−1 removed
- other:+181 added−70 removed
Provenance
- Commit
ffbcb3e- Tree
0ee1703- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
223429f
19 files changed+268 added−71 removed
added:examples/serve-static/assets/static/demo/index.html+6 added
123456<html> <body> <h1>Hello Hono!</h1> <img src="/static/images/dinotocat.png" alt="Dinotocat" /> </body></html>added:examples/serve-static/assets/static/images/dinotocat.pngbinary
A binary file, added.
added:examples/serve-static/assets/static/hello.txt+1 added
1+This is hello.txt! You can access: /static/demo/added:examples/serve-static/src/index.js+8 added
12345678import { Hono, Middleware } from '../../../dist'
const hono = new Hono()
hono.use('/static/*', Middleware.serveStatic({ root: './assets' }))hono.get('/', (c) => c.text('This is Home! You can access: /static/hello.txt'))
hono.fire()deleted:examples/serve-static/src/index.ts-18 removed
123456789101112131415161718import { Hono } from '../../../dist'import { getAssetFromKV } from '@cloudflare/kv-asset-handler'
const hono = new Hono()
hono.get('/', (c) => c.text('This is Home! You can access: /static/hello.txt'))
hono.all('/static/*', async (c) => { try { return await getAssetFromKV(c.event) } catch (e) { return c.newResponse('Asset Not Found', { status: 404, }) }})
hono.fire()deleted:examples/serve-static/static/hello.txt-1 removed
1-This is hello.txt!modified:examples/serve-static/package.json+5 added-16 removed
123455678910117891011121316141819202122232425152716{ "name": "hono-example-serve-static", "version": "0.0.1", "description": "", "main": "dist/worker.js", "main": "src/index.js", "scripts": { "test": "jest --verbose", "build": "rimraf tsc && wrangler build", "dev": "tsc && npm-run-all --parallel dev:*", "dev:tsc": "tsc --watch", "dev:wrangler": "wrangler dev" "test": "echo \"Error: no test specified\" && exit 1", "dev": "wrangler dev", "publish": "wrangler publish" }, "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)", "license": "MIT", "dependencies": { "@cloudflare/kv-asset-handler": "^0.2.0", "hono": "*" }, "devDependencies": { "@cloudflare/workers-types": "^3.3.0", "@cloudflare/wrangler": "^1.19.7", "npm-run-all": "^4.1.5", "typescript": "^4.5.4", "webpack": "^5.65.0", "webpack-cli": "^4.9.1" }}}No newline at end of filedeleted:examples/serve-static/tsconfig.json-21 removed
123456789101112131415161718192021{ "compilerOptions": { "target": "es2017", "module": "commonjs", "rootDir": "src", "outDir": "./dist", "allowJs": true, "strict": true, "esModuleInterop": true, "skipLibCheck": true, "types": [ "@cloudflare/workers-types", ] }, "include": [ "src/**/*" ], "exclude": [ "node_modules", ]}No newline at end of filedeleted:examples/serve-static/webpack.config.js-4 removed
1234module.exports = { target: 'webworker', entry: './dist/index.js',}modified:examples/serve-static/wrangler.toml-1 removed
4 unmodified lines5 usage_model = ''6 compatibility_flags = []7 workers_dev = true8 compatibility_date = "2022-01-09"9-webpack_config = "webpack.config.js"9 10 [site]11 bucket = "./"12 entry-point = "./"modified:src/middleware/mustache/mustache.ts+1 added-1 removed
22 unmodified lines23 if (!content) {24 throw new Error(`Template "${filename}${EXTENSION}" is not found or blank.`)25 }26 27- const partialArgs: { [name: string]: string } = {}27+ const partialArgs: { [name: string]: any } = {}28 if (options) {29 const partials = options as Partials30 for (const key of Object.keys(partials)) {31 const partialContent = await getContentFromKVAsset(`${partials[key]}${EXTENSION}`)12 unmodified linesadded:src/middleware/serve-static/serve-static.test.ts+68 added
1+import { Hono } from '../../hono'2+import { Middleware } from '../../middleware'3+4+// Mock5+const store: { [key: string]: string } = {6+ 'assets/static/plain.abcdef.txt': 'This is plain.txt',7+ 'assets/static/hono.abcdef.html': '<h1>Hono!</h1>',8+ 'assets/static/top/index.abcdef.html': '<h1>Top</h1>',9+ 'static-no-root/plain.abcdef.txt': 'That is plain.txt',10+}11+const manifest = JSON.stringify({12+ 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',13+ 'assets/static/hono.html': 'assets/static/hono.abcdef.html',14+ 'assets/static/top/index.html': 'assets/static/top/index.abcdef.html',15+ 'static-no-root/plain.txt': 'static-no-root/plain.abcdef.txt',16+})17+18+Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })19+Object.assign(global, {20+ __STATIC_CONTENT: {21+ get: (path: string) => {22+ return store[path]23+ },24+ },25+})26+27+describe('ServeStatic Middleware', () => {28+ const app = new Hono()29+30+ app.use('/static/*', Middleware.serveStatic({ root: './assets' }))31+ app.use('/static-no-root/*', Middleware.serveStatic())32+33+ it('Serve static files', async () => {34+ let req = new Request('http://localhost/static/plain.txt')35+ let res = await app.dispatch(req)36+ expect(res.status).toBe(200)37+ expect(await res.text()).toBe('This is plain.txt')38+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')39+ expect(res.headers.get('Content-Length')).toBe('17')40+41+ req = new Request('http://localhost/static/hono.html')42+ res = await app.dispatch(req)43+ expect(res.status).toBe(200)44+ expect(await res.text()).toBe('<h1>Hono!</h1>')45+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')46+ expect(res.headers.get('Content-Length')).toBe('14')47+48+ req = new Request('http://localhost/static/not-found.html')49+ res = await app.dispatch(req)50+ expect(res.status).toBe(404)51+52+ req = new Request('http://localhost/static-no-root/plain.txt')53+ res = await app.dispatch(req)54+ expect(res.status).toBe(200)55+ expect(await res.text()).toBe('That is plain.txt')56+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')57+ expect(res.headers.get('Content-Length')).toBe('17')58+ })59+60+ it('Serve index.html', async () => {61+ const req = new Request('http://localhost/static/top')62+ const res = await app.dispatch(req)63+ expect(res.status).toBe(200)64+ expect(await res.text()).toBe('<h1>Top</h1>')65+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')66+ expect(res.headers.get('Content-Length')).toBe('12')67+ })68+})added:src/middleware/serve-static/serve-static.ts+51 added
1+import type { Context } from '../../context'2+import { getContentFromKVAsset } from '../../utils/cloudflare'3+import { getMimeType } from '../../utils/mime'4+5+type Options = {6+ root: string7+}8+9+const DEFAULT_DOCUMENT = 'index.html'10+11+// This middleware is available only on Cloudflare Workers.12+export const serveStatic = (opt: Options = { root: '' }) => {13+ return async (c: Context, next: Function) => {14+ await next()15+ const url = new URL(c.req.url)16+17+ const path = getKVPath(url.pathname, opt.root)18+19+ const content = await getContentFromKVAsset(path)20+ if (content) {21+ const mimeType = getMimeType(path)22+ if (mimeType) {23+ c.header('Content-Type', mimeType)24+ }25+ c.res = c.body(content)26+ } else {27+ // console.debug(`Static file: ${path} is not found`)28+ }29+ }30+}31+32+const getKVPath = (filename: string, root: string): string => {33+ if (filename.endsWith('/')) {34+ // /top/ => /top/index.html35+ filename = filename.concat(DEFAULT_DOCUMENT)36+ } else if (!getMimeType(filename)) {37+ // /top => /top/index.html38+ filename = filename.concat('/' + DEFAULT_DOCUMENT)39+ }40+ // /foo.html => foo.html41+ filename = filename.replace(/^\//, '')42+43+ // assets/ => assets44+ root = root.replace(/\/$/, '')45+46+ // ./assets/foo.html => assets/foo.html47+ let path = root + '/' + filename48+ path = path.replace(/^\.?\//, '')49+50+ return path51+}modified:src/utils/cloudflare.test.ts+8 added-1 removed
1 import { getContentFromKVAsset } from './cloudflare'2 3 // Mock4-const store: { [key: string]: string } = { 'index.abcdef.html': 'This is index' }4+const store: { [key: string]: string } = {5+ 'index.abcdef.html': 'This is index',6+ 'assets/static/plain.abcdef.txt': 'Asset text',7+}8 const manifest = JSON.stringify({9 'index.html': 'index.abcdef.html',10+ 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',11 })12 13 Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })14 Object.assign(global, {10 unmodified lines25 expect(content).toBeUndefined()26 content = await getContentFromKVAsset('index.html')27 expect(content).not.toBeUndefined()28 expect(content).toBe('This is index')29+ content = await getContentFromKVAsset('assets/static/plain.txt')30+ expect(content).not.toBeUndefined()31+ expect(content).toBe('Asset text')32 })33 })modified:src/utils/cloudflare.ts+3 added-5 removed
1 declare const __STATIC_CONTENT: KVNamespace, __STATIC_CONTENT_MANIFEST: string2 3-export const getContentFromKVAsset = async (path: string): Promise<string> => {3+export const getContentFromKVAsset = async (path: string): Promise<ArrayBuffer> => {4 let ASSET_MANIFEST: { [key: string]: string }5 if (typeof __STATIC_CONTENT_MANIFEST === 'string') {6 ASSET_MANIFEST = JSON.parse(__STATIC_CONTENT_MANIFEST)7 } else {6 unmodified lines14 if (!key) {15 return16 }17 18- let content: string18+ let content = await ASSET_NAMESPACE.get(key, { type: 'arrayBuffer' })19 20- content = await ASSET_NAMESPACE.get(key, { type: 'text' })21-20 if (content) {23- content = content as string21+ content = content as ArrayBuffer22 }23 return content24 }added:src/utils/mime.test.ts+11 added
1+import { getMimeType } from './mime'2+3+describe('mime', () => {4+ it('getMimeType', () => {5+ expect(getMimeType('hello.txt')).toBe('text/plain; charset=utf-8')6+ expect(getMimeType('hello.html')).toBe('text/html; charset=utf-8')7+ expect(getMimeType('hello.json')).toBe('application/json; charset=utf-8')8+ expect(getMimeType('good.morning.hello.gif')).toBe('image/gif')9+ expect(getMimeType('goodmorninghellogif')).toBeUndefined()10+ })11+})added:src/utils/mime.ts+89 added
1+export const getMimeType = (filename: string): string => {2+ const regexp = /\.([a-zA-Z0-9]+?)$/3+ const match = filename.match(regexp)4+ if (!match) {5+ return6+ }7+ let mimeType = mimes[match[1]]8+ if (mimeType.startsWith('text') || mimeType === 'application/json') {9+ mimeType += '; charset=utf-8'10+ }11+ return mimeType12+}13+14+const mimes: { [extension: string]: string } = {15+ aac: 'audio/aac',16+ abw: 'application/x-abiword',17+ arc: 'application/x-freearc',18+ avi: 'video/x-msvideo',19+ azw: 'application/vnd.amazon.ebook',20+ bin: 'application/octet-stream',21+ bmp: 'image/bmp',22+ bz: 'application/x-bzip',23+ bz2: 'application/x-bzip2',24+ csh: 'application/x-csh',25+ css: 'text/css',26+ csv: 'text/csv',27+ doc: 'application/msword',28+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',29+ eot: 'application/vnd.ms-fontobject',30+ epub: 'application/epub+zip',31+ gz: 'application/gzip',32+ gif: 'image/gif',33+ htm: 'text/html',34+ html: 'text/html',35+ ico: 'image/vnd.microsoft.icon',36+ ics: 'text/calendar',37+ jar: 'application/java-archive',38+ jpeg: 'image/jpeg',39+ jpg: 'image/jpeg',40+ js: 'text/javascript',41+ json: 'application/json',42+ jsonld: 'application/ld+json',43+ mid: 'audio/x-midi',44+ midi: 'audio/x-midi',45+ mjs: 'text/javascript',46+ mp3: 'audio/mpeg',47+ mpeg: 'video/mpeg',48+ mpkg: 'application/vnd.apple.installer+xml',49+ odp: 'application/vnd.oasis.opendocument.presentation',50+ ods: 'application/vnd.oasis.opendocument.spreadsheet',51+ odt: 'application/vnd.oasis.opendocument.text',52+ oga: 'audio/ogg',53+ ogv: 'video/ogg',54+ ogx: 'application/ogg',55+ opus: 'audio/opus',56+ otf: 'font/otf',57+ png: 'image/png',58+ pdf: 'application/pdf',59+ php: 'application/php',60+ ppt: 'application/vnd.ms-powerpoint',61+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',62+ rar: 'application/vnd.rar',63+ rtf: 'application/rtf',64+ sh: 'application/x-sh',65+ svg: 'image/svg+xml',66+ swf: 'application/x-shockwave-flash',67+ tar: 'application/x-tar',68+ tif: 'image/tiff',69+ tiff: 'image/tiff',70+ ts: 'video/mp2t',71+ ttf: 'font/ttf',72+ txt: 'text/plain',73+ vsd: 'application/vnd.visio',74+ wav: 'audio/wav',75+ weba: 'audio/webm',76+ webm: 'video/webm',77+ webp: 'image/webp',78+ woff: 'font/woff',79+ woff2: 'font/woff2',80+ xhtml: 'application/xhtml+xml',81+ xls: 'application/vnd.ms-excel',82+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',83+ xml: 'application/xml',84+ xul: 'application/vnd.mozilla.xul+xml',85+ zip: 'application/zip',86+ '3gp': 'video/3gpp',87+ '3g2': 'video/3gpp2',88+ '7z': 'application/x-7z-compressed',89+}modified:src/context.ts+15 added-3 removed
38 unmodified lines39 newResponse(data: any, init: ResponseInit = {}): Response {40 init.status = init.status || this._status41 init.statusText = init.statusText || this._statusText42 43- const Encoder = new TextEncoder()44- const length = data ? data.bytelength || Encoder.encode(data).byteLength : 045- init.headers = { ...this._headers, ...init.headers, ...{ 'Content-Length': String(length) } }43+ init.headers = { ...this._headers, ...init.headers }44 45+ // Content-Length46+ let length = 047+ if (data) {48+ if (data instanceof ArrayBuffer) {49+ length = data.byteLength50+ } else if (typeof data == 'string') {51+ const Encoder = new TextEncoder()52+ length = Encoder.encode(data).byteLength || 053+ } else {54+ length = data.bytelength55+ }56+ }57+ init.headers = { ...init.headers, ...{ 'Content-Length': length.toString() } }58+59 return new Response(data, init)60 }61 62 body(data: any, status: number = this._status, headers: Headers = this._headers): Response {50 unmodified linesmodified:src/middleware.ts+2 added
4 unmodified lines5 import { bodyParse } from './middleware/body-parse/body-parse'6 import { cors } from './middleware/cors/cors'7 import { cookie } from './middleware/cookie/cookie'8 import { mustache } from './middleware/mustache/mustache'9+import { serveStatic } from './middleware/serve-static/serve-static'10 11 export class Middleware {12 static default = defaultMiddleware13 static poweredBy = poweredBy2 unmodified lines16 static bodyParse = bodyParse17 static cors = cors18 static cookie = cookie19 static mustache = mustache20+ static serveStatic = serveStatic21 }