diff options
author | Liam Perlaki <lperlaki@icloud.com> | 2019-11-06 18:18:28 +0100 |
---|---|---|
committer | Ry Dahl <ry@tinyclouds.org> | 2019-11-06 12:18:28 -0500 |
commit | ccc9f1ae5ea3d7ec858ff2eeab490aafaa089d36 (patch) | |
tree | b2433d175a37149b7322f2f358d402b3472f8192 | |
parent | 5c1deac0cfe66ef27020aa0e863c16f3bc2afb50 (diff) |
Allow http server to take { hostname, port } argument (#3233)
-rw-r--r-- | std/http/server.ts | 49 |
1 files changed, 34 insertions, 15 deletions
diff --git a/std/http/server.ts b/std/http/server.ts index 9e2184351..db4150ef5 100644 --- a/std/http/server.ts +++ b/std/http/server.ts @@ -383,10 +383,28 @@ export class Server implements AsyncIterable<ServerRequest> { } } -export function serve(addr: string): Server { - // TODO(ry) Update serve to also take { hostname, port }. - const [hostname, port] = addr.split(":"); - const listener = listen({ hostname, port: Number(port) }); +interface ServerConfig { + port: number; + hostname?: string; +} + +/** + * Start a HTTP server + * + * import { serve } from "https://deno.land/std/http/server.ts"; + * const body = new TextEncoder().encode("Hello World\n"); + * const s = serve({ port: 8000 }); + * for await (const req of s) { + * req.respond({ body }); + * } + */ +export function serve(addr: string | ServerConfig): Server { + if (typeof addr === "string") { + const [hostname, port] = addr.split(":"); + addr = { hostname, port: Number(port) }; + } + + const listener = listen(addr); return new Server(listener); } @@ -406,19 +424,20 @@ export type HTTPSOptions = Omit<Deno.ListenTLSOptions, "transport">; /** * Create an HTTPS server with given options + * + * 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 }); + * } + * * @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 = { |