Merge pull request #239 from honojs/develop
Before adoption: this commit came in with the history the project adopted, so no landing records it.
for v1.3.0
authored by Yusuke Wada · committed by GitHub · parents b314348, f14ec5d · Browse files · 7 files·+403 added−214 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+403 added−214 removed
- tests:+230 added−117 removed
- other:+173 added−97 removed
Provenance
- Commit
bc7fce4- Tree
37b694f- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
b314348- Parent 2
f14ec5d
7 files changed+403 added−214 removed
modified:src/middleware/cookie/index.test.ts+78 added-47 removed
1234565678989101112131415101117181920211213141516171819202324252122232724252629303132272834353637383929303132333435364137383943444546474849505140414243444546474849505153525354555657585960616263646566676869707172737475767778798081828384855657585960616286878889909192939495import { Hono } from '../../hono'import { cookie } from '.'
describe('Cookie Middleware', () => { const app = new Hono() app.use('/cookie', cookie()) describe('Parse cookie', () => { const apps: Record<string, Hono> = {} apps['get by name'] = (() => { const app = new Hono()
app.get('/cookie', (c) => { const yummyCookie = c.req.cookie('yummy_cookie') const tastyCookie = c.req.cookie('tasty_cookie') const res = new Response('Good cookie') res.headers.set('Yummy-Cookie', yummyCookie) res.headers.set('Tasty-Cookie', tastyCookie) return res }) app.use('/cookie', cookie())
it('Parse cookie on c.req.cookie', async () => { const req = new Request('http://localhost/cookie') const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry ' req.headers.set('Cookie', cookieString) const res = await app.request(req) app.get('/cookie', (c) => { const yummyCookie = c.req.cookie('yummy_cookie') const tastyCookie = c.req.cookie('tasty_cookie') const res = new Response('Good cookie') res.headers.set('Yummy-Cookie', yummyCookie) res.headers.set('Tasty-Cookie', tastyCookie) return res })
expect(res.headers.get('Yummy-Cookie')).toBe('choco') expect(res.headers.get('Tasty-Cookie')).toBe('strawberry') }) return app })()
app.use('/set-cookie', cookie()) apps['get all as an object'] = (() => { const app = new Hono()
app.get('/set-cookie', (c) => { c.cookie('delicious_cookie', 'macha') return c.text('Give cookie') }) app.use('/cookie', cookie())
it('Set cookie on c.cookie', async () => { const res = await app.request('http://localhost/set-cookie') expect(res.status).toBe(200) const header = res.headers.get('Set-Cookie') expect(header).toBe('delicious_cookie=macha') }) app.get('/cookie', (c) => { const { yummy_cookie: yummyCookie, tasty_cookie: tastyCookie } = c.req.cookie() const res = new Response('Good cookie') res.headers.set('Yummy-Cookie', yummyCookie) res.headers.set('Tasty-Cookie', tastyCookie) return res })
app.use('/set-cookie-complex', cookie()) return app })()
app.get('/set-cookie-complex', (c) => { c.cookie('great_cookie', 'banana', { path: '/', secure: true, domain: 'example.com', httpOnly: true, maxAge: 1000, expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)), sameSite: 'Strict', describe.each(Object.keys(apps))('%s', (name) => { const app = apps[name] it('Parse cookie on c.req.cookie', async () => { const req = new Request('http://localhost/cookie') const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry ' req.headers.set('Cookie', cookieString) const res = await app.request(req)
expect(res.headers.get('Yummy-Cookie')).toBe('choco') expect(res.headers.get('Tasty-Cookie')).toBe('strawberry') }) }) return c.text('Give cookie') })
describe('Set cookie', () => { const app = new Hono()
app.use('/set-cookie', cookie())
app.get('/set-cookie', (c) => { c.cookie('delicious_cookie', 'macha') return c.text('Give cookie') })
it('Set cookie on c.cookie', async () => { const res = await app.request('http://localhost/set-cookie') expect(res.status).toBe(200) const header = res.headers.get('Set-Cookie') expect(header).toBe('delicious_cookie=macha') })
app.use('/set-cookie-complex', cookie())
app.get('/set-cookie-complex', (c) => { c.cookie('great_cookie', 'banana', { path: '/', secure: true, domain: 'example.com', httpOnly: true, maxAge: 1000, expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)), sameSite: 'Strict', }) return c.text('Give cookie') })
it('Complex pattern', async () => { const res = await app.request('http://localhost/set-cookie-complex') expect(res.status).toBe(200) const header = res.headers.get('Set-Cookie') expect(header).toBe( 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict' ) it('Complex pattern', async () => { const res = await app.request('http://localhost/set-cookie-complex') expect(res.status).toBe(200) const header = res.headers.get('Set-Cookie') expect(header).toBe( 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict' ) }) })})modified:src/middleware/cookie/index.ts+12 added-5 removed
12345667891011121315 unmodified lines2930313230333435363334353738394041424344454648 unmodified linesimport type { Context } from '../../context'import type { Next } from '../../hono'
declare global { interface Request { cookie: (name: string) => string cookie: { (name: string): string (): Record<string, string> } }}
declare module '../../context' {15 unmodified lines}
export const cookie = () => { return async (c: Context, next: Next) => { c.req.cookie = (name: string): string => { c.req.cookie = ((name?: string): string | Record<string, string> => { const cookie = c.req.headers.get('Cookie') const obj = parse(cookie) if (name) { const value = obj[name] return value } const value = obj[name] return value } else { return obj } }) as typeof c.req.cookie c.cookie = (name: string, value: string, opt?: CookieOptions) => { const cookie = serialize(name, value, opt) c.header('Set-Cookie', cookie) }48 unmodified linesmodified:src/context.ts+25 added-8 removed
5 unmodified lines6 type Data = string | ArrayBuffer | ReadableStream7 8 export type Env = Record<string, any>9 10-export class Context<RequestParamKeyType = string, E = Env> {10+export class Context<RequestParamKeyType extends string = string, E = Env> {11 req: Request<RequestParamKeyType>12 res: Response = undefined13 env: E14 event: FetchEvent18 unmodified lines33 this._map = {}34 Object.assign(this, opts)35 }36 37- private initRequest<T>(req: Request<T>): Request<T> {38- req.header = (name: string): string => {39- return req.headers.get(name)40- }41- req.query = (key: string): string => {37+ private initRequest<T extends string>(req: Request<T>): Request<T> {38+ req.header = ((name?: string): string | Record<string, string> => {39+ if (name) {40+ return req.headers.get(name)41+ } else {42+ const result: Record<string, string> = {}43+ for (const [key, value] of req.headers) {44+ result[key] = value45+ }46+ return result47+ }48+ }) as typeof req.header49+50+ req.query = ((key?: string): string | Record<string, string> => {51 const url = new URL(req.url)52+ if (key) {53+ return url.searchParams.get(key)54+ } else {55+ const result: Record<string, string> = {}56+ for (const [key, value] of url.searchParams) {57+ result[key] = value58+ }43- return url.searchParams.get(key)44- }59+ return result60+ }61+ }) as typeof req.query62 return req63 }64 65 header(name: string, value: string): void {84 unmodified linesmodified:src/hono.test.ts+152 added-70 removed
1 import type { Context } from './context'2 import type { Next } from './hono'3-import { Hono, Route } from './hono'3+import { Hono } from './hono'4 import { poweredBy } from './middleware/powered-by'5 6 describe('GET Request', () => {7 const app = new Hono()172 unmodified lines180 })181 })182 183 describe('param and query', () => {184+ const apps: Record<string, Hono> = {}185+ apps['get by name'] = (() => {184- const app = new Hono()186+ const app = new Hono()187 186- app.get('/entry/:id', (c) => {187- const id = c.req.param('id')188- return c.text(`id is ${id}`)189- })188+ app.get('/entry/:id', (c) => {189+ const id = c.req.param('id')190+ return c.text(`id is ${id}`)191+ })192 191- app.get('/date/:date{[0-9]+}', (c) => {192- const date = c.req.param('date')193- return c.text(`date is ${date}`)194- })193+ app.get('/date/:date{[0-9]+}', (c) => {194+ const date = c.req.param('date')195+ return c.text(`date is ${date}`)196+ })197 196- app.get('/search', (c) => {197- const name = c.req.query('name')198- return c.text(`name is ${name}`)199- })198+ app.get('/search', (c) => {199+ const name = c.req.query('name')200+ return c.text(`name is ${name}`)201+ })202 201- app.get('/add-header', (c) => {202- const bar = c.req.header('X-Foo')203- return c.text(`foo is ${bar}`)204- })203+ app.get('/add-header', (c) => {204+ const bar = c.req.header('X-Foo')205+ return c.text(`foo is ${bar}`)206+ })207 206- it('param of /entry/:id is found', async () => {207- const res = await app.request('http://localhost/entry/123')208- expect(res.status).toBe(200)209- expect(await res.text()).toBe('id is 123')210- })208+ return app209+ })()210 212- it('param of /date/:date is found', async () => {213- const res = await app.request('http://localhost/date/0401')214- expect(res.status).toBe(200)215- expect(await res.text()).toBe('date is 0401')216- })211+ apps['get all as an object'] = (() => {212+ const app = new Hono()213 218- it('query of /search?name=sam is found', async () => {219- const res = await app.request('http://localhost/search?name=sam')220- expect(res.status).toBe(200)221- expect(await res.text()).toBe('name is sam')222- })214+ app.get('/entry/:id', (c) => {215+ const { id } = c.req.param()216+ return c.text(`id is ${id}`)217+ })218 219+ app.get('/date/:date{[0-9]+}', (c) => {220+ const { date } = c.req.param()221+ return c.text(`date is ${date}`)222+ })223+224+ app.get('/search', (c) => {225+ const { name } = c.req.query()226+ return c.text(`name is ${name}`)227+ })228+229+ app.get('/add-header', (c) => {230+ const { 'x-foo': bar } = c.req.header()231+ return c.text(`foo is ${bar}`)232+ })233+234+ return app235+ })()236+237+ describe.each(Object.keys(apps))('%s', (name) => {238+ const app = apps[name]239+240+ it('param of /entry/:id is found', async () => {241+ const res = await app.request('http://localhost/entry/123')242+ expect(res.status).toBe(200)243+ expect(await res.text()).toBe('id is 123')244+ })245+246+ it('param of /date/:date is found', async () => {247+ const res = await app.request('http://localhost/date/0401')248+ expect(res.status).toBe(200)249+ expect(await res.text()).toBe('date is 0401')250+ })251+252+ it('query of /search?name=sam is found', async () => {253+ const res = await app.request('http://localhost/search?name=sam')254+ expect(res.status).toBe(200)255+ expect(await res.text()).toBe('name is sam')256+ })257+224- it('/add-header header - X-Foo is Bar', async () => {225- const req = new Request('http://localhost/add-header')226- req.headers.append('X-Foo', 'Bar')227- const res = await app.request(req)228- expect(res.status).toBe(200)229- expect(await res.text()).toBe('foo is Bar')258+ it('/add-header header - X-Foo is Bar', async () => {259+ const req = new Request('http://localhost/add-header')260+ req.headers.append('X-Foo', 'Bar')261+ const res = await app.request(req)262+ expect(res.status).toBe(200)263+ expect(await res.text()).toBe('foo is Bar')264+ })265 })266 })267 268 describe('Middleware', () => {302 unmodified lines571 expect(res.headers.get('X-Header-2')).toBe('bar')572 })573 })574 540-describe('`Route` with app.route', () => {541- const app = new Hono()575+describe('Hono with `app.route`', () => {576 describe('Basic', () => {543- const route = new Route()544- route.get('/post', (c) => c.text('GET /POST'))545- route.post('/post', (c) => c.text('POST /POST'))546- app.route('/v1', route)577+ const app = new Hono()578+ const api = new Hono()579+ const middleware = new Hono()580+ api.get('/posts', (c) => c.text('List'))581+ api.post('/posts', (c) => c.text('Create'))582+ api.get('/posts/:id', (c) => c.text(`GET ${c.req.param('id')}`))583+ api.use('*', async (c, next) => {584+ await next()585+ c.res.headers.append('x-custom-a', 'a')586+ })587+ app.route('/api', api)588 589+ middleware.use('*', async (c, next) => {590+ await next()591+ c.res.headers.append('x-custom-b', 'b')592+ })593+594+ app.route('/api', middleware)595+548- it('Should return 200 response - GET /v1/post', async () => {549- const res = await app.request('http://localhost/v1/post')596+ it('Should return not found response', async () => {597+ const res = await app.request('http://localhost/')598+ expect(res.status).toBe(404)599+ })600+601+ it('Should return not found response', async () => {602+ const res = await app.request('http://localhost/posts')603+ expect(res.status).toBe(404)604+ })605+606+ test('GET /api/posts', async () => {607+ const res = await app.request('http://localhost/api/posts')608 expect(res.status).toBe(200)551- expect(await res.text()).toBe('GET /POST')609+ expect(await res.text()).toBe('List')610 })611 554- it('Should return 200 response - POST /v1/post', async () => {555- const res = await app.request('http://localhost/v1/post', { method: 'POST' })612+ test('Custom header by middleware', async () => {613+ const res = await app.request('http://localhost/api/posts')614 expect(res.status).toBe(200)557- expect(await res.text()).toBe('POST /POST')615+ expect(res.headers.get('x-custom-a')).toBe('a')616+ expect(res.headers.get('x-custom-b')).toBe('b')617 })618 560- it('Should return 404 response - DELETE /v1/post', async () => {561- const res = await app.request('http://localhost/v1/post', { method: 'DELETE' })562- expect(res.status).toBe(404)619+ test('POST /api/posts', async () => {620+ const res = await app.request('http://localhost/api/posts', { method: 'POST' })621+ expect(res.status).toBe(200)622+ expect(await res.text()).toBe('Create')623 })624 565- it('Should return 404 response - GET /post', async () => {566- const res = await app.request('http://localhost/post')567- expect(res.status).toBe(404)625+ test('GET /api/posts/123', async () => {626+ const res = await app.request('http://localhost/api/posts/123')627+ expect(res.status).toBe(200)628+ expect(await res.text()).toBe('GET 123')629 })630 })631 632 describe('Chaining', () => {572- const route = new Route()633+ const app = new Hono()634+ const route = new Hono()635 route.get('/post', (c) => c.text('GET /POST v2')).post((c) => c.text('POST /POST v2'))636 app.route('/v2', route)637 638 it('Should return 200 response - GET /v2/post', async () => {13 unmodified lines652 expect(res.status).toBe(404)653 })654 })655 594- describe('Named parameter', () => {595- const route = new Route()596- route.get('/post/:id', (c) => {597- const id = c.req.param('id')598- return c.text(`GET /post/${id} v3`)656+ describe('Nested', () => {657+ const app = new Hono()658+ const api = new Hono()659+ const book = new Hono()660+661+ book.get('/', (c) => c.text('list books'))662+ book.get('/:id', (c) => c.text(`book ${c.req.param('id')}`))663+664+ api.get('/', (c) => c.text('this is API'))665+ api.route('/book', book)666+667+ app.get('/', (c) => c.text('root'))668+ app.route('/v2', api)669+670+ it('Should return 200 response - GET /', async () => {671+ const res = await app.request('http://localhost/')672+ expect(res.status).toBe(200)673+ expect(await res.text()).toBe('root')674 })600- app.route('/v3', route)675 602- it('Should return 200 response - GET /v3/post/1', async () => {603- const res = await app.request('http://localhost/v3/post/1')676+ it('Should return 200 response - GET /v2', async () => {677+ const res = await app.request('http://localhost/v2')678 expect(res.status).toBe(200)605- expect(await res.text()).toBe('GET /post/1 v3')679+ expect(await res.text()).toBe('this is API')680 })681+607- it('Should return 404 response - GET /v3/post', async () => {608- const res = await app.request('http://localhost/v3/post/abc/def')609- expect(res.status).toBe(404)682+ it('Should return 200 response - GET /v2/book', async () => {683+ const res = await app.request('http://localhost/v2/book')684+ expect(res.status).toBe(200)685+ expect(await res.text()).toBe('list books')686 })687+688+ it('Should return 200 response - GET /v2/book/123', async () => {689+ const res = await app.request('http://localhost/v2/book/123')690+ expect(res.status).toBe(200)691+ expect(await res.text()).toBe('book 123')692+ })693 })694 })695 696 describe('Multiple handler', () => {80 unmodified linesmodified:src/hono.ts+45 added-64 removed
6 unmodified lines7 import { TrieRouter } from './router/trie-router' // Default Router8 import { getPathFromURL, mergePath } from './utils/url'9 10 declare global {11- interface Request<ParamKeyType = string> {12- param: (key: ParamKeyType) => string13- query: (key: string) => string14- header: (name: string) => string11+ interface Request<ParamKeyType extends string = string> {12+ param: {13+ (key: ParamKeyType): string14+ (): Record<ParamKeyType, string>15+ }16+ query: {17+ (key: string): string18+ (): Record<string, string>19+ }20+ header: {21+ (name: string): string22+ (): Record<string, string>23+ }24 }25 }26 18-export type Handler<RequestParamKeyType = string, E = Env> = (27+export type Handler<RequestParamKeyType extends string = string, E = Env> = (28 c: Context<RequestParamKeyType, E>,29 next: Next30 ) => Response | Promise<Response> | void | Promise<void>31 export type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response37 unmodified lines69 } {70 return class {} as any71 }72 64-interface Routing<E extends Env> {73+interface Route<E extends Env> {74 path: string66- method: Methods75+ method: string76 handler: Handler<string, E>77 }78 70-export class Route<E = Env, P extends string = ''> extends defineDynamicClass()<E, P, Route<E, P>> {71- routes: Routing<E>[] = []72- #path: string = ''73-74- constructor() {75- super()76- const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]77-78- allMethods.map((method) => {79- this[method] = <Path extends string>(80- args1: Path | Handler<ParamKeys<Path>, E>,81- ...args: [Handler<ParamKeys<Path>, E>]82- ) => {83- if (typeof args1 === 'string') {84- this.#path = args185- } else {86- this.add(method, this.#path, args1)87- }88- args.map((handler) => {89- if (typeof handler !== 'string') {90- this.add(method, this.#path, handler)91- }92- })93- return this94- }95- })96- }97-98- private add(method: Methods, path: string, handler: Handler<string, E>): Route<E, P> {99- const r: Routing<E> = { path: path, method: method, handler: handler }100- this.routes.push(r)101- return this102- }103-}104-105-export class Hono<E = Env, P extends string = ''> extends defineDynamicClass()<E, P, Hono<E, P>> {79+export class Hono<E = Env, P extends string = '/'> extends defineDynamicClass()<E, P, Hono<E, P>> {80 readonly routerClass: { new (): Router<any> } = TrieRouter81 readonly strict: boolean = true // strict routing - default is true108- #router: Router<Handler<string, E>>109- #tempPath: string110- private path: string82+ private _router: Router<Handler<string, E>>83+ private _tempPath: string84+ private path: string = '/'85 86+ routes: Route<E>[] = []87+88 constructor(init: Partial<Pick<Hono, 'routerClass' | 'strict'>> = {}) {89 super()90 91 const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]17 unmodified lines109 })110 111 Object.assign(this, init)112 137- this.#router = new this.routerClass()138- this.#tempPath = null113+ this._router = new this.routerClass()114+ this._tempPath = null115 }116 117 private notFoundHandler: NotFoundHandler = (c: Context) => {118 const message = '404 Not Found'5 unmodified lines124 const message = 'Internal Server Error'125 return c.text(message, 500)126 }127 152- route(path: string, route?: Route<any>): Hono<E, P> {153- const newHono: Hono<E, P> = new Hono()154- newHono.#tempPath = path155- newHono.#router = this.#router156-157- if (route) {158- route.routes.map((r) => {159- newHono.addRoute(r.method, r.path, r.handler)128+ route(path: string, app?: Hono<any>): Hono<E, P> {129+ this._tempPath = path130+ if (app) {131+ app.routes.map((r) => {132+ this.addRoute(r.method, r.path, r.handler)133 })134 }135 163- return newHono136+ return this137 }138 139 use(path: string, ...middleware: Handler<string, E>[]): Hono<E, P>140 use(...middleware: Handler<string, E>[]): Hono<E, P>20 unmodified lines161 }162 163 private addRoute(method: string, path: string, handler: Handler<string, E>): void {164 method = method.toUpperCase()192- if (this.#tempPath) {193- path = mergePath(this.#tempPath, path)165+ if (this._tempPath) {166+ path = mergePath(this._tempPath, path)167 }195- this.#router.add(method, path, handler)168+ this._router.add(method, path, handler)169+ const r: Route<E> = { path: path, method: method, handler: handler }170+ this.routes.push(r)171 }172 173 private async matchRoute(method: string, path: string): Promise<Result<Handler<string, E>>> {199- return this.#router.match(method, path)174+ return this._router.match(method, path)175 }176 177 private async dispatch(request: Request, event?: FetchEvent, env?: E): Promise<Response> {178 const path = getPathFromURL(request.url, { strict: this.strict })179 const method = request.method180 181 const result = await this.matchRoute(method, path)207- request.param = (key: string): string => {208- if (result) return result.params[key]209- }182+ request.param = ((key?: string): string | Record<string, string> => {183+ if (result) {184+ if (key) {185+ return result.params[key]186+ } else {187+ return result.params188+ }189+ }190+ }) as typeof request.param191 const handlers = result ? result.handlers : [this.notFoundHandler]192 193 const c = new Context<string, E>(request, { env: env, event: event, res: undefined })194 c.notFound = () => this.notFoundHandler(c)35 unmodified linesmodified:src/index.ts+1 added-1 removed
11234export { Hono, Route } from './hono'export { Hono } from './hono'export type { Handler, Next } from './hono'export { Context } from './context'export type { Env } from './context'modified:README.md+90 added-19 removed
50 unmodified lines51 52 Routers used in Hono are really smart.53 54 - **TrieRouter**(default) - Implemented with Trie tree structure.55-- **RegExpRouter** - Match routes with one big Regex made before dispatching at once.55+- **RegExpRouter** - Match the route with using one big Regex made before dispatch.56 57 ## Hono in 1 minute58 59 A demonstration to create an application for Cloudflare Workers with Hono.32 unmodified lines92 93 And, the routing of Hono is so flexible. It's easy to construct large web applications.94 95 ```ts96-import { Hono, Route } from 'hono'97-import { cors } from 'hono/cors'96+import { Hono } from 'hono'97+import { basicAuth } from 'hono/basic-auth'98 99-const app = new Hono()100-101-const v1 = new Route()99+const v1 = new Hono()100 v1.get('/posts', (c) => {101 return c.text('list pots')102 })105- .post('/posts', cors(), (c) => {103+ .post(basicAuth({ username, password }), (c) => {104 return c.text('created!', 201)105 })106 .get('/posts/:id', (c) => {107 const id = c.req.param('id')108 return c.text(`your id is ${id}`)109 })110 111+const app = new Hono()112 app.route('/v1', v1)113 ```114 115 ### Web Standard22 unmodified lines138 An instance of `Hono` has these methods.139 140 - app.**HTTP_METHOD**(\[path,\] handler|middleware...)141 - app.**all**(\[path,\] handler|middleware...)143-- app.**route**(path, \[Route\])142+- app.**route**(path, \[app\])143 - app.**use**(\[path,\] middleware)144 - app.**notFound**(handler)145 - app.**onError**(err, handler)146 - app.**fire**()7 unmodified lines154 ```ts155 // HTTP Methods156 app.get('/', (c) => c.text('GET /'))157 app.post('/', (c) => c.text('POST /'))158+app.put('/', (c) => c.text('PUT /'))159+app.delete('/', (c) => c.text('DELETE /'))160 161 // Wildcard162 app.get('/wild/*/card', (c) => {163 return c.text('GET /wild/*/card')11 unmodified lines175 ...176 })177 ```178 179+or all parameters at once:180+181+```ts182+app.get('/posts/:id/comment/:comment_id', (c) => {183+ const { id, comment_id } = c.req.param()184+ ...185+})186+```187+188 ### Regexp189 190 ```ts191 app.get('/post/:date{[0-9]+}/:title{[a-z]+}', (c) => {182- const date = c.req.param('date')183- const title = c.req.param('title')192+ const { date, title } = c.req.param()193 ...194 })195 ```196 30 unmodified lines227 return c.text(`Status is ${response.status}`)228 })229 ```230 222-## Route231+## Grouping232 224-`Route` object enables Nested route.233+Group the routes with `Hono` instance and add them to the main app with `route` method.234 235 ```ts227-const book = new Route()236+const book = new Hono()237 238 book.get('/', (c) => c.text('List Books')) // GET /book239 book.get('/:id', (c) => {240 // GET /book/:id1 unmodified line242 return c.text('Get Book: ' + id)243 })244 book.post('/', (c) => c.text('Create Book')) // POST /book245 246+const app = new Hono()247 app.route('/book', book)248 ```249 250 ## Middleware96 unmodified lines347 const query = c.req.query('q')348 ...349 })350 351+// Get all params at once352+app.get('/search', (c) => {353+ const { q, limit, offset } = c.req.query()354+ ...355+})356+357 // Captured params358 app.get('/entry/:id', (c) => {359 const id = c.req.param('id')360 ...81 unmodified lines442 ### c.res443 444 ```ts445 // Response object430-app.use('/', (c, next) => {431- next()446+app.use('/', async (c, next) => {447+ await next()448 c.res.headers.append('X-Debug', 'Debug message')449 })450 ```451 452 ### c.event453 454 ```ts455 // FetchEvent object440-app.use('*', async (c, next) => {456+app.get('/foo', async (c) => {457 c.event.waitUntil(442- ...458+ c.env.KV.put(key, data)459 )444- await next()460+ ...461 })462 ```463 464 ### c.env109 unmodified lines574 ```575 npx create-cloudflare my-app https://github.com/honojs/hono-minimal576 ```577 562-## Examples578+## Practical Example579 580+How about writing web API with Hono?581+582+```ts583+import { Hono } from 'hono'584+import { cors } from 'hono/cors'585+import { basicAuth } from 'hono/basic-auth'586+import { prettyJSON } from 'hono/pretty-json'587+import { getPosts, getPosts, createPost } from './model'588+589+const app = new Hono()590+app.get('/', (c) => c.text('Pretty Blog API'))591+app.use('*', prettyJSON())592+app.notFound((c) => c.json({ message: 'Not Found', ok: false }, 404))593+594+export interface Bindings {595+ USERNAME: string596+ PASSWORD: string597+}598+599+const api = new Hono<Bindings>()600+601+api.get('/posts', (c) => {602+ const { limit, offset } = c.req.query()603+ const posts = getPosts({ limit, offset })604+ return c.json({ posts })605+})606+607+api.get('/posts/:id', (c) => {608+ const id = c.req.param('id')609+ const post = getPost({ id })610+ return c.json({ post })611+})612+613+api.post(614+ '/posts',615+ async (c, next) => {616+ const auth = basicAuth({ username: c.env.USERNAME, password: c.env.PASSWORD })617+ await auth(c, next)618+ },619+ async (c) => {620+ const post = await c.req.json<POST>()621+ const ok = createPost({ post })622+ return c.json({ ok })623+ }624+)625+626+app.use('/posts/*', cors())627+628+app.route('/api', api)629+630+export default app631+```632+633+## Other Examples634+635 - Hono Examples - <https://github.com/honojs/examples>636 637 ## Related projects638 31 unmodified lines