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