Golang Split Host Port to Separate Variables

Getting just the host or port from the “host:port” form is easy using the SplitHostPort function from the net package.

Below are some example uses of the function. As seen below, IPv6 addresses in hostport must be enclosed in square brackets.

package main

import (
	"fmt"
	"net"
)

func main() {
	// IPv4
	host, port, err := net.SplitHostPort("172.217.7.14:443")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(host, port)
	
	// IPv6
	host, port, err = net.SplitHostPort("[2607:f8b0:4006:800::200e]:443")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(host, port)
	
	// Domain
	host, port, err = net.SplitHostPort("example.com:80")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(host, port)
}

Output:

172.217.7.14 443
2607:f8b0:4006:800::200e 443
example.com 80