Golang / GoLang Production Patterns and Web Standards Interview Questions
How does gRPC work in Go and when would you choose it over REST/JSON?
gRPC is a high-performance RPC framework using Protocol Buffers (binary serialisation) over HTTP/2. Go has first-class gRPC support through google.golang.org/grpc. It is the standard for inter-service communication in Go microservices.
// user.proto defines the service contract
// service UserService {
// rpc GetUser(GetUserRequest) returns (User);
// rpc StreamUsers(Empty) returns (stream User);
// }
// Generated Go code — implement the server interface
type userServiceServer struct {
pb.UnimplementedUserServiceServer // embed for forward compatibility
repo UserRepository
}
func (s *userServiceServer) GetUser(
ctx context.Context,
req *pb.GetUserRequest,
) (*pb.User, error) {
user, err := s.repo.FindByID(ctx, int(req.Id))
if err != nil {
if errors.Is(err, ErrNotFound) {
return nil, status.Errorf(codes.NotFound, "user %d not found", req.Id)
}
return nil, status.Errorf(codes.Internal, "internal error: %v", err)
}
return &pb.User{Id: int64(user.ID), Name: user.Name, Email: user.Email}, nil
}
// Start gRPC server
func main() {
lis, err := net.Listen("tcp", ":9090")
if err != nil { log.Fatal(err) }
grpcServer := grpc.NewServer(
grpc.ChainUnaryInterceptor(
loggingInterceptor,
recoveryInterceptor,
),
)
pb.RegisterUserServiceServer(grpcServer, &userServiceServer{repo: repo})
grpcServer.Serve(lis)
}| Aspect | REST/JSON | gRPC/Protobuf |
|---|---|---|
| Serialisation | JSON (text, ~30 bytes/field) | Protobuf (binary, ~3 bytes/field) |
| Browser support | Native | Requires grpc-web proxy |
| Code generation | Optional | Required (protoc) |
| Streaming | SSE or WebSocket workarounds | Built-in bidirectional streaming |
| Best for | Public APIs, browser clients | Internal service-to-service RPC |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
