From 0644f9c1a6fd85831dac459f50306781ac2b08e3 Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Mon, 4 Nov 2019 13:45:29 -0500 Subject: std/http: add serveTLS and listenAndServeTLS (#3257) --- std/http/server.ts | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) (limited to 'std/http/server.ts') 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; + +/** + * 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 { + const server = serveTLS(options); + + for await (const request of server) { + handler(request); + } +} + export interface Response { status?: number; headers?: Headers; -- cgit v1.2.3