-
Notifications
You must be signed in to change notification settings - Fork 1
/
example.ts
96 lines (87 loc) · 2.7 KB
/
example.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
92
93
94
95
96
import { ConnInfo, serve_http, serve_https } from "./mod.ts";
import { copy } from "https://deno.land/std@0.178.0/streams/copy.ts";
import { writeAll } from "https://deno.land/std@0.178.0/streams/write_all.ts";
export function upgrade(req: Request, connInfo: ConnInfo) {
const { socket, response } = Deno.upgradeWebSocket(req);
const { url, headers, method } = req;
const data = {
...connInfo,
url,
method,
headers: Object.fromEntries(headers),
};
const body = JSON.stringify(data);
console.log("upgrade", body);
socket.addEventListener("open", () => {
socket.send(body);
socket.close();
});
return response;
}
export { request as request };
function request(req: Request, connInfo: ConnInfo): Response {
const { url, headers, method } = req;
const data = {
...connInfo,
url,
method,
headers: Object.fromEntries(headers),
};
const body = JSON.stringify(data);
console.log("request", body);
return new Response(body, {
headers: { "content-type": "application/json" },
});
}
export async function connect(
request: Request,
connInfo: ConnInfo,
): Promise<Response> {
const { url, headers, method } = request;
const data = {
...connInfo,
url,
method,
headers: Object.fromEntries(headers),
};
const body = JSON.stringify(data);
console.log("connect", body);
const req = request;
const { port, hostname } = new URL(req.url);
const connect_port = port ? Number(port) : 80;
try {
const socket: Deno.TcpConn = await Deno.connect({
port: connect_port,
hostname,
});
Deno.upgradeHttp(request).then(async ([conn, firstPacket]) => {
try {
await writeAll(conn, firstPacket);
await Promise.race([copy(conn, socket), copy(socket, conn)]);
} catch (error) {
console.error(error);
} finally {
socket.close();
conn.close();
}
});
return new Response(null, { status: 200 });
} catch (e) {
console.error(String(e));
return new Response("503", { status: 503 });
}
}
export const handlers = { upgrade, connect, request: request };
export const key = await (
await fetch("https://unpkg.com/self-signed-cert@1.0.1/key.pem")
).text();
export const cert = await (
await fetch("https://unpkg.com/self-signed-cert@1.0.1/cert.pem")
).text();
// console.log(cert, key);
if (import.meta.main) {
await Promise.all([
serve_http(handlers, { port: 18080 }),
serve_https(handlers, { port: 18443, cert, key }),
]);
}