forked from honojs/hono
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
71 lines (64 loc) · 1.7 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* @module
* Trailing Slash Middleware for Hono.
*/
import type { MiddlewareHandler } from '../../types'
/**
* Trailing Slash Middleware for Hono.
*
* @see {@link https://hono.dev/docs/middleware/builtin/trailing-slash}
*
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use(trimTrailingSlash())
* app.get('/about/me/', (c) => c.text('With Trailing Slash'))
* ```
*/
export const trimTrailingSlash = (): MiddlewareHandler => {
return async function trimTrailingSlash(c, next) {
await next()
if (
c.res.status === 404 &&
(c.req.method === 'GET' || c.req.method === 'HEAD') &&
c.req.path !== '/' &&
c.req.path.at(-1) === '/'
) {
const url = new URL(c.req.url)
url.pathname = url.pathname.substring(0, url.pathname.length - 1)
c.res = c.redirect(url.toString(), 301)
}
}
}
/**
* Append trailing slash middleware for Hono.
* Append a trailing slash to the URL if it doesn't have one. For example, `/path/to/page` will be redirected to `/path/to/page/`.
*
* @see {@link https://hono.dev/docs/middleware/builtin/trailing-slash}
*
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use(appendTrailingSlash())
* ```
*/
export const appendTrailingSlash = (): MiddlewareHandler => {
return async function appendTrailingSlash(c, next) {
await next()
if (
c.res.status === 404 &&
(c.req.method === 'GET' || c.req.method === 'HEAD') &&
c.req.path.at(-1) !== '/'
) {
const url = new URL(c.req.url)
url.pathname += '/'
c.res = c.redirect(url.toString(), 301)
}
}
}