diff options
author | Kevin (Kun) "Kassimo" Qian <kevinkassimo@gmail.com> | 2019-11-04 13:45:29 -0500 |
---|---|---|
committer | Ry Dahl <ry@tinyclouds.org> | 2019-11-04 13:45:29 -0500 |
commit | 0644f9c1a6fd85831dac459f50306781ac2b08e3 (patch) | |
tree | 677ed1199280db6c1b5b7535883055ededd9a0a8 /std/http/server.ts | |
parent | 0049d4e50c9dd945f25f69b08b08fbf492001f96 (diff) |
std/http: add serveTLS and listenAndServeTLS (#3257)
Diffstat (limited to 'std/http/server.ts')
-rw-r--r-- | std/http/server.ts | 57 |
1 files changed, 56 insertions, 1 deletions
diff --git a/std/http/server.ts b/std/http/server.ts index f1ced0577..9e2184351 100644 --- a/std/http/server.ts +++ b/std/http/server.ts @@ -1,5 +1,5 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -const { listen, copy, toAsyncIterator } = Deno; +const { listen, listenTLS, copy, toAsyncIterator } = Deno; type Listener = Deno.Listener; type Conn = Deno.Conn; type Reader = Deno.Reader; @@ -401,6 +401,61 @@ export async function listenAndServe( } } +/** Options for creating an HTTPS server. */ +export type HTTPSOptions = Omit<Deno.ListenTLSOptions, "transport">; + +/** + * Create an HTTPS server with given options + * @param options Server configuration + * @return Async iterable server instance for incoming requests + * + * const body = new TextEncoder().encode("Hello HTTPS"); + * const options = { + * hostname: "localhost", + * port: 443, + * certFile: "./path/to/localhost.crt", + * keyFile: "./path/to/localhost.key", + * }; + * for await (const req of serveTLS(options)) { + * req.respond({ body }); + * } + */ +export function serveTLS(options: HTTPSOptions): Server { + const tlsOptions: Deno.ListenTLSOptions = { + ...options, + transport: "tcp" + }; + const listener = listenTLS(tlsOptions); + return new Server(listener); +} + +/** + * Create an HTTPS server with given options and request handler + * @param options Server configuration + * @param handler Request handler + * + * const body = new TextEncoder().encode("Hello HTTPS"); + * const options = { + * hostname: "localhost", + * port: 443, + * certFile: "./path/to/localhost.crt", + * keyFile: "./path/to/localhost.key", + * }; + * listenAndServeTLS(options, (req) => { + * req.respond({ body }); + * }); + */ +export async function listenAndServeTLS( + options: HTTPSOptions, + handler: (req: ServerRequest) => void +): Promise<void> { + const server = serveTLS(options); + + for await (const request of server) { + handler(request); + } +} + export interface Response { status?: number; headers?: Headers; |