Skip to content
Myr

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

19 files+268 added−71 removed

added:examples/serve-static/assets/static/demo/index.html+6 added
added:examples/serve-static/assets/static/images/dinotocat.pngbinary

A binary file, added.

added:examples/serve-static/assets/static/hello.txt+1 added
1This is hello.txt! You can access: /static/demo/
added:examples/serve-static/src/index.js+8 added
deleted:examples/serve-static/src/index.ts-18 removed
deleted:examples/serve-static/static/hello.txt-1 removed
1This is hello.txt!
modified:examples/serve-static/package.json+5 added-16 removed
deleted:examples/serve-static/tsconfig.json-21 removed
deleted:examples/serve-static/webpack.config.js-4 removed
modified:examples/serve-static/wrangler.toml-1 removed
4 unmodified lines
5usage_model = ''6compatibility_flags = []7workers_dev = true8compatibility_date = "2022-01-09"9webpack_config = "webpack.config.js"910[site]11bucket = "./"12entry-point = "./"
modified:src/middleware/mustache/mustache.ts+1 added-1 removed
22 unmodified lines
23 if (!content) {24 throw new Error(`Template "${filename}${EXTENSION}" is not found or blank.`)25 }2627 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 lines
added:src/middleware/serve-static/serve-static.test.ts+68 added
1import { Hono } from '../../hono'2import { Middleware } from '../../middleware'34// Mock5const 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}11const 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})1718Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })19Object.assign(global, {20 __STATIC_CONTENT: {21 get: (path: string) => {22 return store[path]23 },24 },25})2627describe('ServeStatic Middleware', () => {28 const app = new Hono()2930 app.use('/static/*', Middleware.serveStatic({ root: './assets' }))31 app.use('/static-no-root/*', Middleware.serveStatic())3233 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')4041 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')4748 req = new Request('http://localhost/static/not-found.html')49 res = await app.dispatch(req)50 expect(res.status).toBe(404)5152 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 })5960 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
1import type { Context } from '../../context'2import { getContentFromKVAsset } from '../../utils/cloudflare'3import { getMimeType } from '../../utils/mime'45type Options = {6 root: string7}89const DEFAULT_DOCUMENT = 'index.html'1011// This middleware is available only on Cloudflare Workers.12export const serveStatic = (opt: Options = { root: '' }) => {13 return async (c: Context, next: Function) => {14 await next()15 const url = new URL(c.req.url)1617 const path = getKVPath(url.pathname, opt.root)1819 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}3132const 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(/^\//, '')4243 // assets/ => assets44 root = root.replace(/\/$/, '')4546 // ./assets/foo.html => assets/foo.html47 let path = root + '/' + filename48 path = path.replace(/^\.?\//, '')4950 return path51}
modified:src/utils/cloudflare.test.ts+8 added-1 removed
1import { getContentFromKVAsset } from './cloudflare'23// Mock4const store: { [key: string]: string } = { 'index.abcdef.html': 'This is index' }4const store: { [key: string]: string } = {5 'index.abcdef.html': 'This is index',6 'assets/static/plain.abcdef.txt': 'Asset text',7}8const manifest = JSON.stringify({9 'index.html': 'index.abcdef.html',10 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',11})1213Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })14Object.assign(global, {
10 unmodified lines
25 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
1declare const __STATIC_CONTENT: KVNamespace, __STATIC_CONTENT_MANIFEST: string23export const getContentFromKVAsset = async (path: string): Promise<string> => {3export 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 lines
14 if (!key) {15 return16 }1718 let content: string18 let content = await ASSET_NAMESPACE.get(key, { type: 'arrayBuffer' })1920 content = await ASSET_NAMESPACE.get(key, { type: 'text' })2120 if (content) {23 content = content as string21 content = content as ArrayBuffer22 }23 return content24}
added:src/utils/mime.test.ts+11 added
1import { getMimeType } from './mime'23describe('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
1export 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}1314const 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 lines
39 newResponse(data: any, init: ResponseInit = {}): Response {40 init.status = init.status || this._status41 init.statusText = init.statusText || this._statusText4243 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 }4445 // 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() } }5859 return new Response(data, init)60 }6162 body(data: any, status: number = this._status, headers: Headers = this._headers): Response {
50 unmodified lines
modified:src/middleware.ts+2 added
4 unmodified lines
5import { bodyParse } from './middleware/body-parse/body-parse'6import { cors } from './middleware/cors/cors'7import { cookie } from './middleware/cookie/cookie'8import { mustache } from './middleware/mustache/mustache'9import { serveStatic } from './middleware/serve-static/serve-static'1011export class Middleware {12 static default = defaultMiddleware13 static poweredBy = poweredBy
2 unmodified lines
16 static bodyParse = bodyParse17 static cors = cors18 static cookie = cookie19 static mustache = mustache20 static serveStatic = serveStatic21}