Skip to content

Commit

Permalink
parsing the hostPort will default the port to 4222 if the platform's …
Browse files Browse the repository at this point in the history
…URL#port doesn't report default ports for a protocol even if specified in the URL (like 80 or 443).

FIX nats-io/nats.js#478
  • Loading branch information
aricart committed Jan 30, 2022
1 parent 5bf5482 commit 0a3f40c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
13 changes: 11 additions & 2 deletions nats-base-client/servers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { isIP } from "./ipparser.ts";
function hostPort(
u: string,
): { listen: string; hostname: string; port: number } {
u = u.trim();
// remove any protocol that may have been provided
if (u.match(/^(.*:\/\/)(.*)/m)) {
u = u.replace(/^(.*:\/\/)(.*)/gm, "$2");
Expand All @@ -36,12 +37,20 @@ function hostPort(
// that means that protocols other than HTTP/S are not
// parsable correctly.
const url = new URL(`http://${u}`);

let sport = "";
if (!url.port) {
url.port = `${DEFAULT_PORT}`;
if (u.endsWith(":80")) {
sport = "80";
} else if (u.endsWith(":443")) {
sport = "443";
} else {
url.port = `${DEFAULT_PORT}`;
}
}
const listen = url.host;
const hostname = url.hostname;
const port = parseInt(url.port, 10);
const port = sport !== "" ? parseInt(sport, 10) : parseInt(url.port, 10);

return { listen, hostname, port };
}
Expand Down
1 change: 1 addition & 0 deletions tests/jsm_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
import { connect } from "../src/mod.ts";
import { assertThrowsAsyncErrorCode, notCompatible } from "./helpers/mod.ts";
import { validateName } from "../nats-base-client/jsutil.ts";
import { JsMsgImpl } from "../nats-base-client/jsmsg.ts";

const StreamNameRequired = "stream name required";
const ConsumerNameRequired = "durable name required";
Expand Down
13 changes: 12 additions & 1 deletion tests/servers_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/
import { Servers } from "../nats-base-client/servers.ts";
import { assertEquals } from "https://deno.land/std@0.95.0/testing/asserts.ts";
import type { ServerInfo } from "../nats-base-client/internal_mod.ts";
import type { ServerInfo } from "../nats-base-client/types.ts";
import { setTransportFactory } from "../nats-base-client/internal_mod.ts";

Deno.test("servers - single", () => {
Expand Down Expand Up @@ -110,3 +110,14 @@ Deno.test("servers - save tls name", () => {
assertEquals(sn.tlsName, "h");
});
});

Deno.test("servers - port 80", () => {
function t(hp: string, port: number) {
let servers = new Servers([hp]);
assertEquals(servers.getCurrentServer().port, port);
}
t("localhost:80", 80);
t("localhost:443", 443);
t("localhost:201", 201);
t("localhost", 4222);
});

0 comments on commit 0a3f40c

Please sign in to comment.