SplitHostPort Parses Listen Addresses

net.SplitHostPort splits host from port: bracketed IPv6 parses cleanly, a missing port or bare IPv6 returns a *net.AddrError with the reason.

GoCli Tooling

Code

gosnippet
25 lines
package main

import (
	"fmt"
	"net"
)

func main() {
	for _, addr := range []string{"db.internal:5432", "[2001:db8::1]:443", "127.0.0.1:8080"} {
		host, port, err := net.SplitHostPort(addr)
		if err != nil {
			fmt.Println("error:", err)
			continue
		}
		fmt.Printf("host=%s port=%s\n", host, port)
	}

	// 缺端口与裸 IPv6(没加方括号)都会报错,错误类型是 *net.AddrError
	if _, _, err := net.SplitHostPort("db.internal"); err != nil {
		fmt.Println("addr error:", err.(*net.AddrError).Err)
	}
	if _, _, err := net.SplitHostPort("2001:db8::1"); err != nil {
		fmt.Println("addr error:", err.(*net.AddrError).Err)
	}
}

How it works

SplitHostPort Parses Listen Addresses reduces to the function main.

Iteration happens inside for _, addr := range []string{"db.internal:5432", "[2001:db8::1]:443", "127.0.0.1:8080"} — everything outside it runs once. err is inspected at 3 call sites before any result is trusted.

Caveats

  • Self-contained — no imports beyond what the runtime already provides.

Using it

The callable shape is func main()

Each run prints the 3 labeled blocks error:, host=, addr error: in source order.

Key statements

for _, addr := range []string{"db.internal:5432", "[2001:db8::1]:443", "127.0.0.1:8080"} {
	host, port, err := net.SplitHostPort(addr)
	if err != nil {
		fmt.Println("error:", err)
		continue
	}
	fmt.Printf("host=%s port=%s\n", host, port)
}

Interactive Tools for This Topic

FAQ

What does SplitHostPort Parses Listen Addresses print when run?
The script runs standalone; its 3 labeled outputs include `error:`, `host=`, `addr error:`.