Skip to content

Commit

Permalink
perf: imprve default host for windows, docker and wsl (#126)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Sep 14, 2023
1 parent c37be8a commit 4d43b30
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
9 changes: 5 additions & 4 deletions src/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { colors } from "consola/utils";
import { consola } from "consola";
import { ListenOptions } from "./types";
import { isWsl } from "./lib/wsl";
import { isDocker } from "./lib/docker";

export function getNetworkInterfaces(includeIPV6?: boolean): string[] {
const addrs = new Set<string>();
Expand Down Expand Up @@ -73,9 +74,9 @@ export function generateURL(
}

export function getDefaultHost(preferPublic?: boolean) {
// Prefer IPV4 stack for Windows and WSL to avoid performance issues
if (process.platform === "win32" || isWsl()) {
return preferPublic ? "0.0.0.0" : "127.0.0.1";
// Prefer default host for docker and wsl
if (isDocker() || isWsl()) {
return "";
}
// For local, use "localhost" to be developer friendly and allow loopback customization}
// For public, use "" to listen on all NIC interfaces (IPV4 and IPV6)
Expand Down Expand Up @@ -135,7 +136,7 @@ const HOSTNAME_RE = /^(?!-)[\d.:A-Za-z-]{1,63}(?<!-)$/;

export function validateHostname(hostname: string, _public: boolean) {
if (hostname && !HOSTNAME_RE.test(hostname)) {
const fallbackHost = _public ? "0.0.0.0" : "127.0.0.1";
const fallbackHost = _public ? "" : "localhost";
consola.warn(
`[listhen] Invalid hostname \`${hostname}\`. Using \`${fallbackHost}\` as fallback.`,
);
Expand Down
4 changes: 3 additions & 1 deletion src/listen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import {
validateHostname,
} from "./_utils";
import { resolveCertificate } from "./_cert";
import { isWsl } from "./lib/wsl";
import { isDocker } from "./lib/docker";

export async function listen(
handle: RequestListener,
Expand Down Expand Up @@ -76,7 +78,7 @@ export async function listen(
)} with public option disabled.`,
);
listhenOptions.public = false;
} else if (!listhenOptions.public && _anyhost) {
} else if (!listhenOptions.public && _anyhost && !(isWsl() || isDocker())) {
consola.warn(
`[listhen] Trying to listhen on public host ${JSON.stringify(
listhenOptions.hostname,
Expand Down

0 comments on commit 4d43b30

Please sign in to comment.