1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-31 19:44:10 -05:00

Allow http server to take { hostname, port } argument (#3233)

This commit is contained in:
Liam Perlaki 2019-11-06 18:18:28 +01:00 committed by Ry Dahl
parent 5c1deac0cf
commit ccc9f1ae5e

View file

@ -383,10 +383,28 @@ export class Server implements AsyncIterable<ServerRequest> {
} }
} }
export function serve(addr: string): Server { interface ServerConfig {
// TODO(ry) Update serve to also take { hostname, port }. port: number;
const [hostname, port] = addr.split(":"); hostname?: string;
const listener = listen({ hostname, port: Number(port) }); }
/**
* 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); return new Server(listener);
} }
@ -406,19 +424,20 @@ export type HTTPSOptions = Omit<Deno.ListenTLSOptions, "transport">;
/** /**
* Create an HTTPS server with given options * 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 * @param options Server configuration
* @return Async iterable server instance for incoming requests * @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 { export function serveTLS(options: HTTPSOptions): Server {
const tlsOptions: Deno.ListenTLSOptions = { const tlsOptions: Deno.ListenTLSOptions = {