Go gRPC
Definisi
gRPC adalah RPC framework berbasis HTTP/2 dengan kontrak protobuf (.proto). Di Go, protoc + plugin go-grpc menghasilkan stub; server mengimplementasikan interface, client memanggil seperti fungsi lokal.
Kapan dipakai
Pakai untuk komunikasi antar-service internal (microservice) yang butuh performa tinggi & kontrak kuat. Hindari untuk publik browser (butuh grpc-web proxy) atau API publik sederhana (REST/JSON lebih mudah).
Cara kerja
Proto
syntax = "proto3";
package api;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest { string name = 1; }
message HelloReply { string message = 1; }Server
func (s *server) SayHello(ctx context.Context, in *api.HelloRequest) (*api.HelloReply, error) {
return &api.HelloReply{Message: "Halo " + in.Name}, nil
}
// lis := net.Listen; grpc.NewServer(); api.RegisterGreeterServer(s, &server{}); s.Serve(lis)Client
conn, _ := grpc.Dial("localhost:50051", grpc.WithInsecure())
c := api.NewGreeterClient(conn)
r, _ := c.SayHello(context.Background(), &api.HelloRequest{Name: "Budi"})Struktur alur
Loading diagram...
Catatan implementasi
- Generate:
protoc --go_out=. --go-grpc_out=. *.proto. grpc.WithInsecure()deprecated; pakaicredentialsuntuk produksi (TLS).- Selain unary, ada server/client streaming & bidirectional — cocok realtime.
- Proto versioning: jangan ubah nomor field; tambah field baru (backward compatible).
Kesalahan umum
- Ubah field number: merusak kompatibilitas serialisasi.
- Tanpa TLS di produksi: man-in-the-middle; pakai credentials.
- Blocking dial tanpa context: hang; selalu timeout.
- Lupa generate ulang stub: kode tidak cocok proto terbaru.