normalization.go raw

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