Split Host Port Handles IPv6 Brackets
SplitHostPort separates host and port with required brackets for IPv6 literals, and JoinHostPort adds them back when joining either address family.
Code
package main
import (
"fmt"
"net"
)
func main() {
// IPv4:host:port 直接拆分
host, port, err := net.SplitHostPort("10.0.0.7:5432")
fmt.Println("v4:", host, port, err)
// IPv6 地址本身带冒号:必须用方括号包裹才能区分端口
host, port, err = net.SplitHostPort("[2001:db8::1]:443")
fmt.Println("v6:", host, port, err)
// 缺端口:SplitHostPort 返回错误而不是猜一个
_, _, err = net.SplitHostPort("2001:db8::1")
fmt.Println("missing port:", err != nil)
// JoinHostPort 反向拼回:IPv6 自动补上方括号
fmt.Println("join v4:", net.JoinHostPort("127.0.0.1", "8080"))
fmt.Println("join v6:", net.JoinHostPort("2001:db8::1", "8080"))
}Walking through the code
The working parts are the function main — everything else is wiring.
Watch out for
- The dependency list is empty — the language runtime covers everything.
Applying it
The signature worth starting from: func main()
Output lines are prefixed (v4:, v6:, missing port:), which makes the effect of each step easy to see.
Statements that matter
host, port, err = net.SplitHostPort("[2001:db8::1]:443")
Interactive Tools for This Topic
Bracket BalancerCheck whether parentheses, square brackets, and braces are balanced, reporting mismatches and maximum nesting depth.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.
FAQ
- What does Split Host Port Handles IPv6 Brackets print when run?
- The script runs standalone; its 5 labeled outputs include `v4:`, `v6:`, `missing port:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.