Last active
October 27, 2016 09:54
-
-
Save cagatay/72c76b427aa41399b13db8d91f60b21e to your computer and use it in GitHub Desktop.
Example server/client for gRPC presentation in Go Meetup Berlin October 2016
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
syntax = "proto3"; | |
option go_package = "sisu.sh/go/pb"; | |
message Baby { | |
// Name of the baby | |
string name = 1; | |
// Expected birthdate | |
string birthdate = 2; | |
} | |
message Greeting { | |
// Text content of greeting | |
string content = 1; | |
} | |
service BabyGreeter { | |
// Greet greets the baby by also calculating the days until birthdate | |
rpc Greet (Baby) returns (Greeting) {} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import grpc | |
import greeter_pb2 | |
channel = grpc.insecure_channel('localhost:5999') | |
stub = greeter_pb2.BabyGreeterStub(channel) | |
baby = greeter_pb2.Baby( | |
name="Leyla", | |
birthdate="2017-03-20" | |
) | |
greeting = stub.Greet(baby) | |
print(greeting.content) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"net" | |
"time" | |
"golang.org/x/net/context" | |
"google.golang.org/grpc" | |
"sisu.sh/go/pb" | |
) | |
// GreeterService is the struct for Greeter service implementation | |
type GreeterService struct{} | |
// Greet greets user | |
func (s *GreeterService) Greet(ctx context.Context, in *pb.Baby) (*pb.Greeting, error) { | |
fmt.Printf("Received message %+v\n", in) | |
t, err := time.Parse("2006-01-02", in.Birthdate) | |
if err != nil { | |
return nil, err | |
} | |
days := int(t.Sub(time.Now()).Hours() / 24) | |
content := fmt.Sprintf("Hello %v, we will meet after %v days.", in.Name, days) | |
return &pb.Greeting{Content: content}, nil | |
} | |
func main() { | |
grpcs := grpc.NewServer() | |
server := &GreeterService{} | |
pb.RegisterBabyGreeterServer(grpcs, server) | |
lis, err := net.Listen("tcp", ":5999") | |
if err != nil { | |
log.Fatal(err) | |
} | |
grpcs.Serve(lis) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment