deno.land / std@0.177.1 / http / server.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.import { delay } from "../async/mod.ts";
/** Thrown by Server after it has been closed. */const ERROR_SERVER_CLOSED = "Server closed";
/** Default port for serving HTTP. */const HTTP_PORT = 80;
/** Default port for serving HTTPS. */const HTTPS_PORT = 443;
/** Initial backoff delay of 5ms following a temporary accept failure. */const INITIAL_ACCEPT_BACKOFF_DELAY = 5;
/** Max backoff delay of 1s following a temporary accept failure. */const MAX_ACCEPT_BACKOFF_DELAY = 1000;
/** Information about the connection a request arrived on. */export interface ConnInfo { /** The local address of the connection. */ readonly localAddr: Deno.Addr; /** The remote address of the connection. */ readonly remoteAddr: Deno.Addr;}
/** * A handler for HTTP requests. Consumes a request and connection information * and returns a response. * * If a handler throws, the server calling the handler will assume the impact * of the error is isolated to the individual request. It will catch the error * and close the underlying connection. */export type Handler = ( request: Request, connInfo: ConnInfo,) => Response | Promise<Response>;
/** Options for running an HTTP server. */export interface ServerInit extends Partial<Deno.ListenOptions> { /** The handler to invoke for individual HTTP requests. */ handler: Handler;
/** * The handler to invoke when route handlers throw an error. * * The default error handler logs and returns the error in JSON format. */ onError?: (error: unknown) => Response | Promise<Response>;}
/** Used to construct an HTTP server. */export class Server { #port?: number; #host?: string; #handler: Handler; #closed = false; #listeners: Set<Deno.Listener> = new Set(); #acceptBackoffDelayAbortController = new AbortController(); #httpConnections: Set<Deno.HttpConn> = new Set(); #onError: (error: unknown) => Response | Promise<Response>;
/** * Constructs a new HTTP Server instance. * * ```ts * import { Server } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * * const port = 4505; * const handler = (request: Request) => { * const body = `Your user-agent is:\n\n${request.headers.get( * "user-agent", * ) ?? "Unknown"}`; * * return new Response(body, { status: 200 }); * }; * * const server = new Server({ port, handler }); * ``` * * @param serverInit Options for running an HTTP server. */ constructor(serverInit: ServerInit) { this.#port = serverInit.port; this.#host = serverInit.hostname; this.#handler = serverInit.handler; this.#onError = serverInit.onError ?? function (error: unknown) { console.error(error); return new Response("Internal Server Error", { status: 500 }); }; }
/** * Accept incoming connections on the given listener, and handle requests on * these connections with the given handler. * * HTTP/2 support is only enabled if the provided Deno.Listener returns TLS * connections and was configured with "h2" in the ALPN protocols. * * Throws a server closed error if called after the server has been closed. * * Will always close the created listener. * * ```ts * import { Server } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * * const handler = (request: Request) => { * const body = `Your user-agent is:\n\n${request.headers.get( * "user-agent", * ) ?? "Unknown"}`; * * return new Response(body, { status: 200 }); * }; * * const server = new Server({ handler }); * const listener = Deno.listen({ port: 4505 }); * * console.log("server listening on http://localhost:4505"); * * await server.serve(listener); * ``` * * @param listener The listener to accept connections from. */ async serve(listener: Deno.Listener) { if (this.#closed) { throw new Deno.errors.Http(ERROR_SERVER_CLOSED); }
this.#trackListener(listener);
try { return await this.#accept(listener); } finally { this.#untrackListener(listener);
try { listener.close(); } catch { // Listener has already been closed. } } }
/** * Create a listener on the server, accept incoming connections, and handle * requests on these connections with the given handler. * * If the server was constructed without a specified port, 80 is used. * * If the server was constructed with the hostname omitted from the options, the * non-routable meta-address `0.0.0.0` is used. * * Throws a server closed error if the server has been closed. * * ```ts * import { Server } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * * const port = 4505; * const handler = (request: Request) => { * const body = `Your user-agent is:\n\n${request.headers.get( * "user-agent", * ) ?? "Unknown"}`; * * return new Response(body, { status: 200 }); * }; * * const server = new Server({ port, handler }); * * console.log("server listening on http://localhost:4505"); * * await server.listenAndServe(); * ``` */ async listenAndServe() { if (this.#closed) { throw new Deno.errors.Http(ERROR_SERVER_CLOSED); }
const listener = Deno.listen({ port: this.#port ?? HTTP_PORT, hostname: this.#host ?? "0.0.0.0", transport: "tcp", });
return await this.serve(listener); }
/** * Create a listener on the server, accept incoming connections, upgrade them * to TLS, and handle requests on these connections with the given handler. * * If the server was constructed without a specified port, 443 is used. * * If the server was constructed with the hostname omitted from the options, the * non-routable meta-address `0.0.0.0` is used. * * Throws a server closed error if the server has been closed. * * ```ts * import { Server } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * * const port = 4505; * const handler = (request: Request) => { * const body = `Your user-agent is:\n\n${request.headers.get( * "user-agent", * ) ?? "Unknown"}`; * * return new Response(body, { status: 200 }); * }; * * const server = new Server({ port, handler }); * * const certFile = "/path/to/certFile.crt"; * const keyFile = "/path/to/keyFile.key"; * * console.log("server listening on https://localhost:4505"); * * await server.listenAndServeTls(certFile, keyFile); * ``` * * @param certFile The path to the file containing the TLS certificate. * @param keyFile The path to the file containing the TLS private key. */ async listenAndServeTls(certFile: string, keyFile: string) { if (this.#closed) { throw new Deno.errors.Http(ERROR_SERVER_CLOSED); }
const listener = Deno.listenTls({ port: this.#port ?? HTTPS_PORT, hostname: this.#host ?? "0.0.0.0", certFile, keyFile, transport: "tcp", // ALPN protocol support not yet stable. // alpnProtocols: ["h2", "http/1.1"], });
return await this.serve(listener); }
/** * Immediately close the server listeners and associated HTTP connections. * * Throws a server closed error if called after the server has been closed. */ close() { if (this.#closed) { throw new Deno.errors.Http(ERROR_SERVER_CLOSED); }
this.#closed = true;
for (const listener of this.#listeners) { try { listener.close(); } catch { // Listener has already been closed. } }
this.#listeners.clear();
this.#acceptBackoffDelayAbortController.abort();
for (const httpConn of this.#httpConnections) { this.#closeHttpConn(httpConn); }
this.#httpConnections.clear(); }
/** Get whether the server is closed. */ get closed(): boolean { return this.#closed; }
/** Get the list of network addresses the server is listening on. */ get addrs(): Deno.Addr[] { return Array.from(this.#listeners).map((listener) => listener.addr); }
/** * Responds to an HTTP request. * * @param requestEvent The HTTP request to respond to. * @param connInfo Information about the underlying connection. */ async #respond( requestEvent: Deno.RequestEvent, connInfo: ConnInfo, ) { let response: Response; try { // Handle the request event, generating a response. response = await this.#handler(requestEvent.request, connInfo);
if (response.bodyUsed && response.body !== null) { throw new TypeError("Response body already consumed."); } } catch (error: unknown) { // Invoke onError handler when request handler throws. response = await this.#onError(error); }
try { // Send the response. await requestEvent.respondWith(response); } catch { // `respondWith()` can throw for various reasons, including downstream and // upstream connection errors, as well as errors thrown during streaming // of the response content. In order to avoid false negatives, we ignore // the error here and let `serveHttp` close the connection on the // following iteration if it is in fact a downstream connection error. } }
/** * Serves all HTTP requests on a single connection. * * @param httpConn The HTTP connection to yield requests from. * @param connInfo Information about the underlying connection. */ async #serveHttp(httpConn: Deno.HttpConn, connInfo: ConnInfo) { while (!this.#closed) { let requestEvent: Deno.RequestEvent | null;
try { // Yield the new HTTP request on the connection. requestEvent = await httpConn.nextRequest(); } catch { // Connection has been closed. break; }
if (requestEvent === null) { // Connection has been closed. break; }
// Respond to the request. Note we do not await this async method to // allow the connection to handle multiple requests in the case of h2. this.#respond(requestEvent, connInfo); }
this.#closeHttpConn(httpConn); }
/** * Accepts all connections on a single network listener. * * @param listener The listener to accept connections from. */ async #accept(listener: Deno.Listener) { let acceptBackoffDelay: number | undefined;
while (!this.#closed) { let conn: Deno.Conn;
try { // Wait for a new connection. conn = await listener.accept(); } catch (error) { if ( // The listener is closed. error instanceof Deno.errors.BadResource || // TLS handshake errors. error instanceof Deno.errors.InvalidData || error instanceof Deno.errors.UnexpectedEof || error instanceof Deno.errors.ConnectionReset || error instanceof Deno.errors.NotConnected ) { // Backoff after transient errors to allow time for the system to // recover, and avoid blocking up the event loop with a continuously // running loop. if (!acceptBackoffDelay) { acceptBackoffDelay = INITIAL_ACCEPT_BACKOFF_DELAY; } else { acceptBackoffDelay *= 2; }
if (acceptBackoffDelay >= MAX_ACCEPT_BACKOFF_DELAY) { acceptBackoffDelay = MAX_ACCEPT_BACKOFF_DELAY; }
try { await delay(acceptBackoffDelay, { signal: this.#acceptBackoffDelayAbortController.signal, }); } catch (err: unknown) { // The backoff delay timer is aborted when closing the server. if (!(err instanceof DOMException && err.name === "AbortError")) { throw err; } }
continue; }
throw error; }
acceptBackoffDelay = undefined;
// "Upgrade" the network connection into an HTTP connection. let httpConn: Deno.HttpConn;
try { httpConn = Deno.serveHttp(conn); } catch { // Connection has been closed. continue; }
// Closing the underlying listener will not close HTTP connections, so we // track for closure upon server close. this.#trackHttpConnection(httpConn);
const connInfo: ConnInfo = { localAddr: conn.localAddr, remoteAddr: conn.remoteAddr, };
// Serve the requests that arrive on the just-accepted connection. Note // we do not await this async method to allow the server to accept new // connections. this.#serveHttp(httpConn, connInfo); } }
/** * Untracks and closes an HTTP connection. * * @param httpConn The HTTP connection to close. */ #closeHttpConn(httpConn: Deno.HttpConn) { this.#untrackHttpConnection(httpConn);
try { httpConn.close(); } catch { // Connection has already been closed. } }
/** * Adds the listener to the internal tracking list. * * @param listener Listener to track. */ #trackListener(listener: Deno.Listener) { this.#listeners.add(listener); }
/** * Removes the listener from the internal tracking list. * * @param listener Listener to untrack. */ #untrackListener(listener: Deno.Listener) { this.#listeners.delete(listener); }
/** * Adds the HTTP connection to the internal tracking list. * * @param httpConn HTTP connection to track. */ #trackHttpConnection(httpConn: Deno.HttpConn) { this.#httpConnections.add(httpConn); }
/** * Removes the HTTP connection from the internal tracking list. * * @param httpConn HTTP connection to untrack. */ #untrackHttpConnection(httpConn: Deno.HttpConn) { this.#httpConnections.delete(httpConn); }}
/** Additional serve options. */export interface ServeInit extends Partial<Deno.ListenOptions> { /** An AbortSignal to close the server and all connections. */ signal?: AbortSignal;
/** The handler to invoke when route handlers throw an error. */ onError?: (error: unknown) => Response | Promise<Response>;
/** The callback which is called when the server started listening */ onListen?: (params: { hostname: string; port: number }) => void;}
/** * Constructs a server, accepts incoming connections on the given listener, and * handles requests on these connections with the given handler. * * ```ts * import { serveListener } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * * const listener = Deno.listen({ port: 4505 }); * * console.log("server listening on http://localhost:4505"); * * await serveListener(listener, (request) => { * const body = `Your user-agent is:\n\n${request.headers.get( * "user-agent", * ) ?? "Unknown"}`; * * return new Response(body, { status: 200 }); * }); * ``` * * @param listener The listener to accept connections from. * @param handler The handler for individual HTTP requests. * @param options Optional serve options. */export async function serveListener( listener: Deno.Listener, handler: Handler, options?: Omit<ServeInit, "port" | "hostname">,) { const server = new Server({ handler, onError: options?.onError });
options?.signal?.addEventListener("abort", () => server.close(), { once: true, });
return await server.serve(listener);}
function hostnameForDisplay(hostname: string) { // If the hostname is "0.0.0.0", we display "localhost" in console // because browsers in Windows don't resolve "0.0.0.0". // See the discussion in https://github.com/denoland/deno_std/issues/1165 return hostname === "0.0.0.0" ? "localhost" : hostname;}
/** Serves HTTP requests with the given handler. * * You can specify an object with a port and hostname option, which is the * address to listen on. The default is port 8000 on hostname "0.0.0.0". * * The below example serves with the port 8000. * * ```ts * import { serve } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * serve((_req) => new Response("Hello, world")); * ``` * * You can change the listening address by the `hostname` and `port` options. * The below example serves with the port 3000. * * ```ts * import { serve } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * serve((_req) => new Response("Hello, world"), { port: 3000 }); * ``` * * `serve` function prints the message `Listening on http://<hostname>:<port>/` * on start-up by default. If you like to change this message, you can specify * `onListen` option to override it. * * ```ts * import { serve } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * serve((_req) => new Response("Hello, world"), { * onListen({ port, hostname }) { * console.log(`Server started at http://${hostname}:${port}`); * // ... more info specific to your server .. * }, * }); * ``` * * You can also specify `undefined` or `null` to stop the logging behavior. * * ```ts * import { serve } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * serve((_req) => new Response("Hello, world"), { onListen: undefined }); * ``` * * @param handler The handler for individual HTTP requests. * @param options The options. See `ServeInit` documentation for details. */export async function serve( handler: Handler, options: ServeInit = {},) { let port = options.port ?? 8000; const hostname = options.hostname ?? "0.0.0.0"; const server = new Server({ port, hostname, handler, onError: options.onError, });
options?.signal?.addEventListener("abort", () => server.close(), { once: true, });
const s = server.listenAndServe();
port = (server.addrs[0] as Deno.NetAddr).port;
if ("onListen" in options) { options.onListen?.({ port, hostname }); } else { console.log(`Listening on http://${hostnameForDisplay(hostname)}:${port}/`); }
return await s;}
export interface ServeTlsInit extends ServeInit { /** Server private key in PEM format */ key?: string;
/** Cert chain in PEM format */ cert?: string;
/** The path to the file containing the TLS private key. */ keyFile?: string;
/** The path to the file containing the TLS certificate */ certFile?: string;}
/** Serves HTTPS requests with the given handler. * * You must specify `key` or `keyFile` and `cert` or `certFile` options. * * You can specify an object with a port and hostname option, which is the * address to listen on. The default is port 8443 on hostname "0.0.0.0". * * The below example serves with the default port 8443. * * ```ts * import { serveTls } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * * const cert = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n"; * const key = "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"; * serveTls((_req) => new Response("Hello, world"), { cert, key }); * * // Or * * const certFile = "/path/to/certFile.crt"; * const keyFile = "/path/to/keyFile.key"; * serveTls((_req) => new Response("Hello, world"), { certFile, keyFile }); * ``` * * `serveTls` function prints the message `Listening on https://<hostname>:<port>/` * on start-up by default. If you like to change this message, you can specify * `onListen` option to override it. * * ```ts * import { serveTls } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * const certFile = "/path/to/certFile.crt"; * const keyFile = "/path/to/keyFile.key"; * serveTls((_req) => new Response("Hello, world"), { * certFile, * keyFile, * onListen({ port, hostname }) { * console.log(`Server started at https://${hostname}:${port}`); * // ... more info specific to your server .. * }, * }); * ``` * * You can also specify `undefined` or `null` to stop the logging behavior. * * ```ts * import { serveTls } from "https://deno.land/std@$STD_VERSION/http/server.ts"; * const certFile = "/path/to/certFile.crt"; * const keyFile = "/path/to/keyFile.key"; * serveTls((_req) => new Response("Hello, world"), { * certFile, * keyFile, * onListen: undefined, * }); * ``` * * @param handler The handler for individual HTTPS requests. * @param options The options. See `ServeTlsInit` documentation for details. * @returns */export async function serveTls( handler: Handler, options: ServeTlsInit,) { if (!options.key && !options.keyFile) { throw new Error("TLS config is given, but 'key' is missing."); }
if (!options.cert && !options.certFile) { throw new Error("TLS config is given, but 'cert' is missing."); }
let port = options.port ?? 8443; const hostname = options.hostname ?? "0.0.0.0"; const server = new Server({ port, hostname, handler, onError: options.onError, });
options?.signal?.addEventListener("abort", () => server.close(), { once: true, });
const key = options.key || Deno.readTextFileSync(options.keyFile!); const cert = options.cert || Deno.readTextFileSync(options.certFile!);
const listener = Deno.listenTls({ port, hostname, cert, key, transport: "tcp", // ALPN protocol support not yet stable. // alpnProtocols: ["h2", "http/1.1"], });
const s = server.serve(listener);
port = (server.addrs[0] as Deno.NetAddr).port;
if ("onListen" in options) { options.onListen?.({ port, hostname }); } else { console.log( `Listening on https://${hostnameForDisplay(hostname)}:${port}/`, ); }
return await s;}
std

Version Info

Tagged at
11 months ago