drgomesp / go-libp2p-grpc

⚙ gRPC/Protobuf on Libp2p with gRPC-Gateway support

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

go-libp2p-grpc

madeby Go Report Card build codecov

⚙ gRPC/Protobuf on Libp2p with gRPC-Gateway support.

Table of Contents

Install

go get github.com/drgomesp/go-libp2p-grpc

Features

Usage

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"})

Contributing

PRs accepted.

License

MIT © Daniel Ribeiro

About

⚙ gRPC/Protobuf on Libp2p with gRPC-Gateway support

License:MIT License


Languages

Language:Go 100.0%