-
Notifications
You must be signed in to change notification settings - Fork 0
/
hostinfo.go
86 lines (69 loc) · 1.81 KB
/
hostinfo.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
80
81
82
83
84
85
86
package hostinfo
import (
"context"
"fmt"
"net/http"
"sort"
"time"
libp2pgrpc "github.com/drgomesp/go-libp2p-grpc"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/libp2p/go-libp2p/core/host"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
v1 "github.com/drgomesp/go-libp2p-hostinfo/proto/v1"
)
type Service struct {
v1.UnimplementedHostInfoServiceServer
host host.Host
mux *runtime.ServeMux
gatewayAddr string
}
func WithHttpServeMux(mux *runtime.ServeMux) ServiceOption {
return func(s *Service) {
s.mux = mux
}
}
func NewService(ctx context.Context, host host.Host, opts ...ServiceOption) (*Service, error) {
svc := &Service{host: host, mux: runtime.NewServeMux()}
srv, err := libp2pgrpc.NewGrpcServer(
ctx,
host,
grpc.KeepaliveParams(keepalive.ServerParameters{
Time: time.Second,
Timeout: 3 * time.Second,
}),
)
if err != nil {
return nil, err
}
for _, opt := range opts {
opt(svc)
}
v1.RegisterHostInfoServiceServer(srv, svc)
err = v1.RegisterHostInfoServiceHandlerServer(ctx, svc.mux, svc)
return svc, err
}
func (s *Service) Info(_ context.Context, _ *v1.InfoRequest) (*v1.InfoResponse, error) {
peers := make([]string, 0)
for _, peer := range s.host.Peerstore().Peers() {
if peer.ShortString() != s.host.ID().ShortString() {
peers = append(peers, peer.ShortString())
}
}
sort.Strings(peers)
return &v1.InfoResponse{
Id: s.host.ID().String(),
Addresses: func() []string {
res := make([]string, 0)
for _, addr := range s.host.Addrs() {
res = append(res, fmt.Sprintf("%s/p2p/%s", addr.String(), s.host.ID().String()))
}
return res
}(),
Protocols: s.host.Mux().Protocols(),
Peers: peers,
}, nil
}
func (s *Service) ListenAndServe() error {
return http.ListenAndServe(s.gatewayAddr, s.mux)
}