-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
www.ts
42 lines (36 loc) 路 973 Bytes
/
www.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
import type { Middleware } from "../core.ts";
export interface Options {
add: boolean;
code: 301 | 302;
}
export const defaults: Options = {
add: false,
code: 301,
};
/** Middleware to add/remove the www. domain */
export default function www(userOptions?: Partial<Options>): Middleware {
const options = { ...defaults, ...userOptions };
return async (request, next) => {
const url = new URL(request.url);
if (url.hostname.startsWith("www.")) {
if (!options.add) {
url.hostname = url.hostname.replace("www.", "");
return new Response(null, {
status: options.code,
headers: {
location: url.toString(),
},
});
}
} else if (options.add) {
url.hostname = `www.${url.hostname}`;
return new Response(null, {
status: options.code,
headers: {
location: url.toString(),
},
});
}
return await next(request);
};
}