Skip to content

gRPC Server & Interceptors ​

boot/server/grpc.go and boot/server/middleware/grpc.go run a hardened google.golang.org/grpc server alongside HTTP whenever GRPC_ENABLE=true.


Registration (GRPCRegistry) ​

Any service implementing server.GRPCRegistry is auto-collected by boot/kernel.go via di.AutoCollect[server.GRPCRegistry]():

go
type GRPCRegistry interface {
	Register(s *grpc.Server)
}

Legacy global registration (server.RegisterGRPC(...) and server.GetGRPCRegistries(), guarded by sync.RWMutex) is also merged by NewGRPCServer for backwards compatibility.


Server Features (boot/server/grpc.go) ​

  • Binding: listens on net.JoinHostPort(cfg.GRPC.Host, strconv.Itoa(cfg.GRPC.Port)) (default 127.0.0.1:50051).
  • TLS: when GRPC_TLS_ENABLED=true, loads GRPC_TLS_CERT_FILE and GRPC_TLS_KEY_FILE via credentials.NewServerTLSFromFile. Load errors fail fast on Start().
  • Health Checking: registers standard grpc_health_v1 (health.NewServer()), marks SERVING on start and NOT_SERVING on stop.
  • Reflection: enables reflection.Register(s) when GRPC_REFLECTION=true.
  • Graceful Shutdown: Stop(ctx) closes the owned LimiterStore, calls s.server.GracefulStop(), and falls back to s.server.Stop() if ctx.Done() fires.

Unary & Stream Interceptor Chain ​

middleware.GrpcServerOptions(cfg, store) attaches both ChainUnaryInterceptor and ChainStreamInterceptor in this exact order:

  1. Recovery — catches panics, logs stack trace via zerolog, returns codes.Internal.
  2. Logger — logs Msg("gRPC Request") with method, code, ip (port-stripped), latency (Error level on non-nil error, Info otherwise).
  3. AppKey Auth — reads incoming gRPC metadata x-app-key, validates via ValidateAppKeyValue, returns codes.Unauthenticated if invalid.
  4. Rate Limiter — calls store.Allow(peerIP(ctx)); peerIP uses net.SplitHostPort to strip ephemeral client TCP ports so limits apply per IP rather than per connection. Exceeded limits return codes.ResourceExhausted.

Proto Layout & Codegen ​

Place .proto files at internal/proto/<service>/<service>.proto:

protobuf
option go_package = "github.com/myorg/myapp/internal/proto/<service>/gen";

Run goforge gen:proto <service> to compile .pb.go + _grpc.pb.go into internal/proto/<service>/gen/, generate internal/services/<service>/grpc.go, and register New<Type>GRPC in module.go.

Released under the Apache-2.0 License.