Skip to content

Instantly share code, notes, and snippets.

syntax = "proto3";
package hello;
service HelloService {
rpc SayHello (HelloRequest) returns (HelloResponse);
}
message HelloRequest {
string greeting = 1;
service HelloService {
rpc SayHello (HelloRequest) returns (HelloResponse);
rpc ClientStreamHello (stream HelloRequest) returns (HelloResponse);
rpc ServerStreamHello (HelloRequest) returns (stream HelloResponse);
rpc BidirectionalStreamHello (stream HelloRequest) returns (stream HelloResponse);
}
// Setting a deadline
clientDeadline := time.Now().Add(time.Duration(*deadlineMs) * time.Millisecond)
ctx, cancel := context.WithDeadline(ctx, clientDeadline)
// Checking deadline
if ctx.Err() == context.Canceled {
return status.New(codes.Canceled, "Client cancelled, abandoning.")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
cancel()
log.Printf("RPC Status : %s", ctx.Err())
Code Name HTTP Mapping
0 OK 200 OK
1 CANCELLED 499 Client Closed Request
2 UNKNOWN 500 Internal Server Error
3 INVALID_ARGUMENT 400 Bad Request
4 DEADLINE_EXCEEDED 504 Gateway Timeout
5 NOT_FOUND 404 Not Found
6 ALREADY_EXISTS 409 Conflict
7 PERMISSION_DENIED 403 Forbidden
grpcServer := grpc.NewServer()
// Register Product Service
product_pb.RegisterProductServer(grpcServer, &productServer{})
// Register Billing Service
billing_pb.RegisterBillingServer(grpcServer, &billingServer{})
// Example of Unary Interceptor
func exampleUnaryServerInterceptor(ctx context.Context, req interface{},
info *grpc.UnaryServerInfo, handler grpc.UnaryHandler)
(interface{}, error) {
// Codes before executing GRPC
log.Println("Some messages before execution")
// Usual execution of a unary RPC
m, err := handler(ctx, req)
type wrappedStream struct { 1
grpc.ServerStream
}
func newWrappedStream(s grpc.ServerStream) grpc.ServerStream {
return &wrappedStream{s}
}
func (w *wrappedStream) RecvMsg(m interface{}) error {
------
func exampleUnaryClientInterceptor(ctx context.Context, method string, req, reply interface{},
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
// Codes before executing GRPC
log.Println("Some messages before execution")
// usual invocation of the remote method
err := invoker(ctx, method, req, reply, cc, opts...)
type wrappedStream struct {
grpc.ClientStream
}
func newWrappedStream(s grpc.ClientStream) grpc.ClientStream {
return &wrappedStream{s}
}
func (w *wrappedStream) RecvMsg(m interface{}) error {
.....