This repository was archived by the owner on Oct 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathregistry.go
79 lines (61 loc) · 1.8 KB
/
registry.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package manet
import (
"fmt"
"net"
"sync"
ma "github.com/jbenet/go-multiaddr"
)
type AddrParser func(a net.Addr) (ma.Multiaddr, error)
type MaddrParser func(ma ma.Multiaddr) (net.Addr, error)
var maddrParsers map[string]MaddrParser
var addrParsers map[string]AddrParser
var addrParsersLock sync.Mutex
type AddressSpec struct {
// NetNames is an array of strings that may be returned
// by net.Addr.Network() calls on addresses belonging to this type
NetNames []string
// Key is the string value for Multiaddr address keys
Key string
// ParseNetAddr parses a net.Addr belonging to this type into a multiaddr
ParseNetAddr AddrParser
// ConvertMultiaddr converts a multiaddr of this type back into a net.Addr
ConvertMultiaddr MaddrParser
// Protocol returns the multiaddr protocol struct for this type
Protocol ma.Protocol
}
func RegisterAddressType(a *AddressSpec) {
addrParsersLock.Lock()
defer addrParsersLock.Unlock()
for _, n := range a.NetNames {
addrParsers[n] = a.ParseNetAddr
}
maddrParsers[a.Key] = a.ConvertMultiaddr
}
func init() {
addrParsers = make(map[string]AddrParser)
maddrParsers = make(map[string]MaddrParser)
RegisterAddressType(tcpAddrSpec)
RegisterAddressType(udpAddrSpec)
RegisterAddressType(utpAddrSpec)
RegisterAddressType(ip4AddrSpec)
RegisterAddressType(ip6AddrSpec)
addrParsers["ip+net"] = parseIpPlusNetAddr
}
func getAddrParser(net string) (AddrParser, error) {
addrParsersLock.Lock()
defer addrParsersLock.Unlock()
parser, ok := addrParsers[net]
if !ok {
return nil, fmt.Errorf("unknown network %v", net)
}
return parser, nil
}
func getMaddrParser(name string) (MaddrParser, error) {
addrParsersLock.Lock()
defer addrParsersLock.Unlock()
p, ok := maddrParsers[name]
if !ok {
return nil, fmt.Errorf("network not supported: %s", name)
}
return p, nil
}