-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
router.ts
91 lines (85 loc) 路 2.65 KB
/
router.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Copyright 2019 Yusuke Sakurai. All rights reserved. MIT license.
import { listenAndServe, ServeOptions, ServerRequest } from "./server.ts";
import { encode } from "https://deno.land/std@v0.3.2/strings/strings.ts";
export type RoutedServerRequest = ServerRequest & {
match?: RegExpMatchArray;
};
/** basic handler for http request */
export type HttpHandler = (req: RoutedServerRequest) => unknown;
/**
* Find the match that appeared in the nearest position to the beginning of word.
* If positions are same, the longest one will be picked.
* Return -1 and null if no match found.
* */
export function findLongestAndNearestMatch(
pathname: string,
patterns: (string | RegExp)[]
): { index: number; match: RegExpMatchArray } {
let lastMatchIndex = pathname.length;
let lastMatchLength = 0;
let match: RegExpMatchArray = null;
let index = -1;
for (let i = 0; i < patterns.length; i++) {
const pattern = patterns[i];
const m = pathname.match(pattern);
if (!m) continue;
if (
m.index < lastMatchIndex ||
(m.index === lastMatchIndex && m[0].length > lastMatchLength)
) {
index = i;
match = m;
lastMatchIndex = m.index;
lastMatchLength = m[0].length;
}
}
return { index, match };
}
export interface HttpRouter {
handle(pattern: string | RegExp, handlers: HttpHandler);
listen(addr: string, opts?: ServeOptions): void;
}
/** create HttpRouter object */
export function createRouter(): HttpRouter {
const routes: { pattern: string | RegExp; handlers: HttpHandler[] }[] = [];
return {
handle(pattern: string | RegExp, ...handlers: HttpHandler[]) {
routes.push({ pattern, handlers });
},
listen(addr: string, opts?: ServeOptions) {
listenAndServe(
addr,
async req => {
let { pathname } = new URL(req.url, addr);
const { index, match } = findLongestAndNearestMatch(
pathname,
routes.map(v => v.pattern)
);
if (index > -1) {
const { handlers } = routes[index];
for (const handler of handlers) {
await handler(Object.assign(req, { match }));
if (req.isResponded()) {
break;
}
}
if (!req.isResponded()) {
await req.respond({
status: 500,
headers: new Headers(),
body: encode("Not Responded")
});
}
} else {
await req.respond({
status: 404,
headers: new Headers(),
body: encode("Not Found")
});
}
},
opts
);
}
};
}