Go's net.SplitHostPort in TypeScript

✓ Verified: Go 1.23
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { SplitHostPort } from 'locutus/golang/net/SplitHostPort'.

Or with CommonJS: const { SplitHostPort } = require('locutus/golang/net/SplitHostPort')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1SplitHostPort('localhost:80')['localhost', '80']
2SplitHostPort('[2001:db8::1]:443')['2001:db8::1', '443']
3SplitHostPort(':8080')['', '8080']

Here's what our current TypeScript equivalent to Go's net.SplitHostPort looks like.

export function SplitHostPort(hostport: string): [string, string] {
// discuss at: https://locutus.io/golang/net/SplitHostPort
// parity verified: Go 1.23
// original by: Kevin van Zonneveld (https://kvz.io)
// example 1: SplitHostPort('localhost:80')
// returns 1: ['localhost', '80']
// example 2: SplitHostPort('[2001:db8::1]:443')
// returns 2: ['2001:db8::1', '443']
// example 3: SplitHostPort(':8080')
// returns 3: ['', '8080']

const value = String(hostport)
if (value.startsWith('[')) {
const close = value.indexOf(']')
if (close < 0 || value[close + 1] !== ':') {
throw new TypeError('SplitHostPort(): invalid host:port')
}

const host = value.slice(1, close)
const port = value.slice(close + 2)
if (port === '') {
throw new TypeError('SplitHostPort(): missing port')
}

return [host, port]
}

const firstColon = value.indexOf(':')
const lastColon = value.lastIndexOf(':')
if (lastColon < 0) {
throw new TypeError('SplitHostPort(): missing port')
}
if (firstColon !== lastColon) {
throw new TypeError('SplitHostPort(): too many colons in address')
}

const host = value.slice(0, lastColon)
const port = value.slice(lastColon + 1)
if (port === '') {
throw new TypeError('SplitHostPort(): missing port')
}

return [host, port]
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


Help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.


« More Go net functions


Star