⚙ gRPC/Protobuf on Libp2p with gRPC-Gateway support.
go get github.com/drgomesp/go-libp2p-grpc
- GRPC/Protobuf support for any Libp2p
host.Host
- GRPC Gateway and OpenAPI/Swagger support through
go-libp2p-http
For a working example with gRPC-gateway support, check the examples/ folder.
Given an RPC service:
service EchoService {
// Echo asks a node to respond with a message.
rpc Echo(EchoRequest) returns (EchoReply) {}
}
type EchoService struct {}
func (EchoService) Echo(context.Context, *EchoRequest) (*EchoReply, error) {
...
}
And a libp2p host to act as the server:
ma, _ := multiaddr.NewMultiaddr("/ip4/127.0.0.1/tcp/10000")
serverHost, err := libp2p.New(libp2p.ListenAddrs(ma))
if err != nil {
log.Fatal(err)
}
defer serverHost.Close()
srv, err := libp2pgrpc.NewGrpcServer(ctx, serverHost)
if err != nil {
log.Fatal(err)
}
Register the gRPC service to the host server:
pb.RegisterEchoServiceServer(srv, &EchoService{})
Start gRPC for serve:
go srv.Serve()
A libp2p host to act as the client:
ma, _ := multiaddr.NewMultiaddr("/ip4/127.0.0.1/tcp/10001")
clientHost, err := libp2p.New(libp2p.ListenAddrs(ma))
if err != nil {
log.Fatal(err)
}
Dial the server and initiate the request:
client := libp2pgrpc.NewClient(cliHost, libp2pgrpc.ProtocolID, libp2pgrpc.WithServer(srv))
conn, err := client.Dial(ctx, serverHost.ID(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
c := pb.NewEchoServiceClient(conn)
res, err := c.Echo(ctx, &pb.EchoRequest{Message: "give me something"})
PRs accepted.
MIT © Daniel Ribeiro