tutorial

Meng-Generate Kode Go dari File Protobuf

gRPC dibangun di atas pondasi kuat bernama Protocol Buffers (protobuf), dan agar file .proto bisa digunakan dalam proyek Go, kita harus mengubahnya menjadi kode Go asli. Proses ini disebut code generation.

Sebagai seorang software engineer, kamu harus memahami bahwa protoc (Protobuf Compiler) tidak hanya sekadar alat bantu — dia adalah jembatan utama yang mentranslasikan kontrak layanan ke dalam bahasa pemrograman yang bisa dieksekusi. Dalam artikel ini, kita akan membahas secara menyeluruh bagaimana cara meng-generate kode Go dari file .proto.


Diagram Alur Proses Generate Proto

flowchart TD
  A[Mulai: Tulis file .proto] --> B[Install protoc & plugin]
  B --> C[Run perintah protoc]
  C --> D1[Generate user.pb.go (message)]
  C --> D2[Generate user_grpc.pb.go (service)]
  D1 & D2 --> E[Import ke Go Project]
  E --> F[Siap digunakan di server & client]

Persiapan: Apa yang Perlu Kamu Install?

Sebelum masuk ke proses generate, pastikan kamu telah meng-install alat berikut:

  1. protoc (Protocol Buffer Compiler)

  2. Plugin Go: protoc-gen-go dan protoc-gen-go-grpc Instal via Go:

    go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
    go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
    
  3. Pastikan GOPATH/bin ada di PATH:

    export PATH="$PATH:$(go env GOPATH)/bin"
    

Struktur Proyek Minimal

Pastikan kamu memiliki struktur direktori seperti ini:

grpc-user/
├── api/
│   └── user.proto
├── go.mod
└── ...

Contoh isi file user.proto:

syntax = "proto3";

package user;
option go_package = "github.com/santekno/grpc-user/api/userpb";

message GetUserRequest {
  string id = 1;
}

message User {
  string id = 1;
  string name = 2;
}

message UserResponse {
  User user = 1;
}

service UserService {
  rpc GetUser (GetUserRequest) returns (UserResponse);
}

Perintah untuk Generate Kode

Di terminal, arahkan ke folder grpc-user lalu jalankan:

protoc \
  --go_out=. \
  --go-grpc_out=. \
  --proto_path=api \
  api/user.proto

Penjelasan:

  • --proto_path=api: folder tempat file .proto berada.
  • --go_out=.: generate kode message ke user.pb.go
  • --go-grpc_out=.: generate service client/server ke user_grpc.pb.go

Setelah dijalankan, akan terbentuk dua file baru di api/:

user.pb.go
user_grpc.pb.go

Isi File user.pb.go

Berisi definisi struct dan enum dari message protobuf:

type GetUserRequest struct {
	Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
}

type User struct {
	Id   string `protobuf:"bytes,1,opt,name=id,proto3"`
	Name string `protobuf:"bytes,2,opt,name=name,proto3"`
}

Isi File user_grpc.pb.go

Berisi interface service dan implementasi server dan client:

type UserServiceClient interface {
	GetUser(ctx context.Context, in *GetUserRequest, opts ...grpc.CallOption) (*UserResponse, error)
}

type UserServiceServer interface {
	GetUser(context.Context, *GetUserRequest) (*UserResponse, error)
}

Tips dan Best Practice

  • Pastikan option go_package di .proto sesuai dengan struktur modul Go (go.mod).
  • Jangan lupa menambahkan userpb sebagai import saat ingin menggunakan hasil generate.
  • Gunakan direktori api/ atau proto/ untuk menjaga konsistensi struktur proyek.

✅ Snippet Testing Hasil Generate (Client/Server)

Server Stub

type userServiceServer struct {
  userpb.UnimplementedUserServiceServer
}

func (s *userServiceServer) GetUser(ctx context.Context, req *userpb.GetUserRequest) (*userpb.UserResponse, error) {
  return &userpb.UserResponse{
    User: &userpb.User{
      Id: req.GetId(),
      Name: "Test User",
    },
  }, nil
}

Client Call

conn, _ := grpc.Dial("localhost:50051", grpc.WithInsecure())
defer conn.Close()

client := userpb.NewUserServiceClient(conn)
res, err := client.GetUser(context.Background(), &userpb.GetUserRequest{Id: "123"})
fmt.Println(res.GetUser().GetName())

✅ Alternatif: Automasi Generate dengan Makefile

Makefile

PROTO_DIR=api
PROTO_FILES=$(PROTO_DIR)/user.proto

generate:
	protoc --proto_path=$(PROTO_DIR) \
	       --go_out=. \
	       --go-grpc_out=. \
	       $(PROTO_FILES)

.PHONY: generate

Jalankan dengan:

make generate

Kesimpulan

Meng-generate kode Go dari file .proto adalah fondasi awal dalam membangun aplikasi berbasis gRPC. Dengan memahami struktur, tools, dan sintaks perintah protoc, kamu membuka pintu menuju komunikasi antar layanan yang kuat, efisien, dan type-safe.

Sebagai seorang developer profesional, memahami tahap ini bukan sekadar opsional — ini adalah investasi kompetensi yang akan kamu gunakan berulang kali dalam pengembangan sistem microservices modern.

Butuh diagram visual dari proses ini atau contoh implementasi lengkap? Tinggal beri tahu, saya siap bantu kamu di artikel berikutnya!


comments powered by Disqus