go install github.com/darmawan01/toldata/cmd/protoc-gen-toldata@latest
This Go module simplifies how you use protobuf with Nats.io:
- Provide proto files
- Provide Go implementations
- Bind the implementation on the server side
- Make a call from the clients
Proto:
message TestARequest {
string input = 1;
}
message TestAResponse {
string output = 1;
}
service TestService {
rpc GetTestA(TestARequest) returns (TestAResponse) {}
}
Implementation:
func (b *TestServiceProtonats) GetTestA(ctx context.Context, req *TestARequest) (*TestAResponse, error) {
...
//some business
...
if err != nil {
return nil, err
}
result := &TestAResponse{
Output: "OK",
}
return result, nil
}
Server side:
Generate the server code from the proto file with --toldata_out=
argument to protoc-gen-go, then:
service := &TestServiceProtonats{}
...
ctx, cancel := context.WithCancel(context.Background())
bus, err := NewBus(ctx, ServiceConfiguration{URL: natsURL, ID: "bus1"})
defer bus.Close()
svr := NewTestServiceProtonatsServer(bus, d)
chan, err = svr.SubscribeTestService()
...
cancel() // cancel services
...
<-chan // wait and unsubscribe
Client side:
Generate the client code from the proto file with --toldata_out=
argument to protoc-gen-go, then:
var client *Bus
client, err = NewBus(ctx, ServiceConfiguration{URL: natsURL})
defer client.Close()
svc := NewTestServiceProtonatsClient(client)
resp, err := svc.GetTestA(ctx, &TestARequest{Input: "OK"})
A GRPC gateway listens GRPC requests and forward them to NATS. The gateway can be generated by generating code from the proto file
with --toldata_out=gprc:
argument to protoc-gen-go. See grpc_test.go
file to check how toimplement the bridge.
This software is licensed under Apache 2 license.
(c) 2019 Citra Digital Lintas