decred.org/dcrwallet/v3@v3.1.0/internal/cfgutil/normalization.go (about)

     1  // Copyright (c) 2015 The btcsuite developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package cfgutil
     6  
     7  import "net"
     8  
     9  // NormalizeAddress returns the normalized form of the address, adding a default
    10  // port if necessary.  An error is returned if the address, even without a port,
    11  // is not valid.
    12  func NormalizeAddress(addr string, defaultPort string) (hostport string, err error) {
    13  	// If the first SplitHostPort errors because of a missing port and not
    14  	// for an invalid host, add the port.  If the second SplitHostPort
    15  	// fails, then a port is not missing and the original error should be
    16  	// returned.
    17  	host, port, origErr := net.SplitHostPort(addr)
    18  	if origErr == nil {
    19  		return net.JoinHostPort(host, port), nil
    20  	}
    21  	addr = net.JoinHostPort(addr, defaultPort)
    22  	_, _, err = net.SplitHostPort(addr)
    23  	if err != nil {
    24  		return "", origErr
    25  	}
    26  	return addr, nil
    27  }
    28  
    29  // NormalizeAddresses returns a new slice with all the passed peer addresses
    30  // normalized with the given default port, and all duplicates removed.
    31  func NormalizeAddresses(addrs []string, defaultPort string) ([]string, error) {
    32  	var (
    33  		normalized = make([]string, 0, len(addrs))
    34  		seenSet    = make(map[string]struct{})
    35  	)
    36  
    37  	for _, addr := range addrs {
    38  		normalizedAddr, err := NormalizeAddress(addr, defaultPort)
    39  		if err != nil {
    40  			return nil, err
    41  		}
    42  		_, seen := seenSet[normalizedAddr]
    43  		if !seen {
    44  			normalized = append(normalized, normalizedAddr)
    45  			seenSet[normalizedAddr] = struct{}{}
    46  		}
    47  	}
    48  
    49  	return normalized, nil
    50  }