protocol buffer golang code example
Example 1: protocol buffers stream golang
package main
import (
"fmt"
"log"
"net"
"sync"
"time"
pb "github.com/pramonow/go-grpc-server-streaming-example/src/proto"
"google.golang.org/grpc"
)
type server struct{}
func (s server) FetchResponse(in *pb.Request, srv pb.StreamService_FetchResponseServer) error {
log.Printf("fetch response for id : %d", in.Id)
//use wait group to allow process to be concurrent
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(count int64) {
defer wg.Done()
//time sleep to simulate server process time
time.Sleep(time.Duration(count) * time.Second)
resp := pb.Response{Result: fmt.Sprintf("Request #%d For Id:%d", count, in.Id)}
if err := srv.Send(&resp); err != nil {
log.Printf("send error %v", err)
}
log.Printf("finishing request number : %d", count)
}(int64(i))
}
wg.Wait()
return nil
}
func main() {
// create listiner
lis, err := net.Listen("tcp", ":50005")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// create grpc server
s := grpc.NewServer()
pb.RegisterStreamServiceServer(s, server{})
log.Println("start server")
// and start...
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
Example 2: protocol buffers stream golang
package main
import (
"context"
"io"
"log"
pb "github.com/pramonow/go-grpc-server-streaming-example/src/proto"
"google.golang.org/grpc"
)
func main() {
// dial server
conn, err := grpc.Dial(":50005", grpc.WithInsecure())
if err != nil {
log.Fatalf("can not connect with server %v", err)
}
// create stream
client := pb.NewStreamServiceClient(conn)
in := &pb.Request{Id: 1}
stream, err := client.FetchResponse(context.Background(), in)
if err != nil {
log.Fatalf("open stream error %v", err)
}
done := make(chan bool)
go func() {
for {
resp, err := stream.Recv()
if err == io.EOF {
done <- true //means stream is finished
return
}
if err != nil {
log.Fatalf("cannot receive %v", err)
}
log.Printf("Resp received: %s", resp.Result)
}
}()
<-done //we will wait until all response is received
log.Printf("finished")
}