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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does SplitHostPort Parses Listen Addresses print when run?
- The script runs standalone; its 3 labeled outputs include `error:`, `host=`, `addr error:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.