Skip to content

Instantly share code, notes, and snippets.

@mohashari
Created March 14, 2026 15:12
Show Gist options
  • Select an option

  • Save mohashari/6feff35fa422c005a0d9b04f1296bf0e to your computer and use it in GitHub Desktop.

Select an option

Save mohashari/6feff35fa422c005a0d9b04f1296bf0e to your computer and use it in GitHub Desktop.
Code snippets — Grpc Vs Rest
func (s *server) Chat(stream pb.ChatService_ChatServer) error {
for {
msg, err := stream.Recv()
if err == io.EOF {
return nil
}
// Broadcast to other users...
stream.Send(&pb.ChatMessage{Content: "echoed: " + msg.Content})
}
}
# Inspect available services
grpcurl -plaintext localhost:50051 list
# Call a method
grpcurl -plaintext -d '{"user_id": "42"}' \
localhost:50051 user.UserService/GetUser
Client → Request → Server
Client ← Response ←
Client ← Response ←
Client ← Response ← Server (stream)
// Server
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer(
grpc.UnaryInterceptor(authInterceptor),
grpc.MaxRecvMsgSize(1024*1024*4),
)
pb.RegisterUserServiceServer(s, &UserServiceServer{db: db})
reflection.Register(s) // Enable grpcurl inspection
log.Printf("gRPC server listening on :50051")
s.Serve(lis)
}
// Client
func main() {
conn, err := grpc.Dial("localhost:50051",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
defer conn.Close()
client := pb.NewUserServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
user, err := client.GetUser(ctx, &pb.GetUserRequest{UserId: "42"})
fmt.Printf("Got user: %v\n", user)
}
Browser/Mobile → REST (via API Gateway) → Internal Services via gRPC
// Server streaming example
func (s *server) ListUsers(req *pb.ListUsersRequest, stream pb.UserService_ListUsersServer) error {
rows, err := db.QueryUsers(req.Filter)
for rows.Next() {
user := scanUser(rows)
if err := stream.Send(user); err != nil {
return err
}
}
return nil
}
// user.proto
syntax = "proto3";
package user;
service UserService {
rpc GetUser(GetUserRequest) returns (User);
rpc ListUsers(ListUsersRequest) returns (stream User);
rpc CreateUser(CreateUserRequest) returns (User);
}
message GetUserRequest {
string user_id = 1;
}
message User {
string id = 1;
string name = 2;
string email = 3;
int64 created_at = 4;
}
protoc --go_out=. --go-grpc_out=. user.proto
Client → Request → Server
Client ← Response ← Server
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment