-
Notifications
You must be signed in to change notification settings - Fork 0
/
peerserver.go
70 lines (56 loc) · 1.6 KB
/
peerserver.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
package main
import (
"gx/ipfs/QmRuZnMorqodado1yeTQiv1i9rmtKj29CjPSsBKM7DFXV4/go-libp2p-net"
"gx/ipfs/QmQa2wf1sLFKkjHCVEbna8y5qhdMjL8vtTJSAc48vZGTer/go-ipfs/core/corenet"
)
// PeerServer asynchronous (non-blocking) server that registers
// handler functions listening to specific endpoints like /health
type PeerServer struct {
*Node
}
// NewPeerServer constructs PeerServer given a node on which the
// server binds its services
func NewPeerServer(node *Node) PeerServer {
return PeerServer{Node: node}
}
// HandleFunc registers a function which get called to handle incoming
// requests triggered on given endpoint
func (p *PeerServer) HandleFunc(endpoint string, handler func(*Node, net.Stream)) error {
list, err := corenet.Listen(p.IpfsNode, endpoint)
if err != nil {
return err
}
Info.Printf("I am peer: %s and listening at %s \n", p.ID, endpoint)
// listen asynchronously
go func() {
for {
// @TODO need to handle error gracefully,
// e.g. tell client that an error occurred
stream, err := list.Accept()
if err != nil {
Error.Println(err)
continue
}
go func(stream net.Stream) {
Info.Printf("Connection from: %s\n", stream.Conn().RemotePeer().Pretty())
defer stream.Close()
isBlacklisted, err := p.IsBlacklisted(p.ID)
if err != nil {
Error.Println(err)
return
}
if isBlacklisted {
Info.Println("Node is blacklisted, abort connection")
return
}
err = p.AddPeer(stream.Conn().RemotePeer().Pretty())
if err != nil {
Error.Println(err)
return
}
handler(p.Node, stream)
}(stream)
}
}()
return nil
}