small pixel drawing of a pufferfish cascade

internal/cli/utils.go

package cli

import (
	"fmt"
	"net"
	"strconv"
	"strings"
)

// parseFlagAddress takes a colon-delimited host:port pair as a string, parses
// out the ip (and optionally, the port), and modifies the passed TCPAddr with
// the resulting values.
func parseFlagAddress(hostPort string, tcpAddr *net.TCPAddr) error {
	addr, portStr, err := net.SplitHostPort(hostPort)
	if err != nil {
		if !strings.Contains(err.Error(), "missing port in address") {
			return fmt.Errorf("Error parsing address: %v", err)
		}

		// If we get a missing port error, we try to coerce the whole hostPort
		// into an address. This allows the user to supply just a host address
		// instead of always requiring a host:ip pair.
		addr = hostPort
	}

	if addr == "" {
		return fmt.Errorf("Error parsing blank address")
	}
	ip := net.ParseIP(addr)
	if ip == nil {
		return fmt.Errorf("Error parsing address %q: not a valid IP address", ip)
	}

	if portStr != "" {
		port, err := strconv.Atoi(portStr)
		if err != nil {
			return fmt.Errorf("Error parsing port: %s", err)
		}
		tcpAddr.Port = port
	}
	tcpAddr.IP = ip

	return nil
}