This program demonstrates the behavior of Go's net.SplitHostPort
function with various input cases.
The net.SplitHostPort
function splits a network address into host and port components. This program tests the function with:
- Standard cases: Regular hostnames and IP addresses with ports
- IPv6 cases: IPv6 addresses properly bracketed
- Edge cases: Boundary port numbers, empty values
- Error cases: Invalid formats that should fail
- JoinHostPort demonstration: Shows the reverse operation and round-trip testing
From running the program, you can see that:
- IPv4 addresses:
127.0.0.1:80
→ Host:127.0.0.1
, Port:80
- Hostnames:
localhost:8080
→ Host:localhost
, Port:8080
- IPv6 addresses: Must be bracketed like
[::1]:8080
→ Host:::1
, Port:8080
- Missing ports: Addresses without ports fail with "missing port in address"
- IPv6 without brackets: Fail with "too many colons in address"
- Port validation: The function doesn't validate port number ranges - it accepts invalid ports like
99999999
or-1
- Empty components: Both host and port can be empty strings
go run main.go
main.go
: The main test programgo.mod
: Go module definitionREADME.md
: This documentation
net.SplitHostPort
is purely a string parsing function - it doesn't validate that ports are in valid ranges (0-65535)- IPv6 addresses must be enclosed in square brackets when combined with ports
- The function is commonly used in network programming when parsing address strings from configuration files or user input