grpc-golang

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

gRPC Golang (gRPC-Go)

gRPC Golang (gRPC-Go)

Overview

概述

Comprehensive guide for designing and implementing production-grade gRPC services in Go. Covers contract standardization with Buf, transport layer security via mTLS, and deep observability with OpenTelemetry interceptors.
这是一份关于在Go中设计和实现生产级gRPC服务的综合指南,涵盖使用Buf进行契约标准化、通过mTLS实现传输层安全,以及借助OpenTelemetry拦截器实现深度可观测性。

Use this skill when

适用场景

  • Designing microservices communication with gRPC in Go.
  • Building high-performance internal APIs using Protobuf.
  • Implementing streaming workloads (unidirectional or bidirectional).
  • Standardizing API contracts using Protobuf and Buf.
  • Configuring mTLS for service-to-service authentication.
  • 在Go中使用gRPC设计微服务通信。
  • 使用Protobuf构建高性能内部API。
  • 实现流式工作负载(单向或双向)。
  • 使用Protobuf和Buf标准化API契约。
  • 配置mTLS以实现服务间身份认证。

Do not use this skill when

不适用场景

  • Building pure REST/HTTP public APIs without gRPC requirements.
  • Modifying legacy
    .proto
    files without the ability to introduce a new API version (e.g.,
    api.v2
    ) or ensure backward compatibility.
  • Managing service mesh traffic routing (e.g., Istio/Linkerd), which is outside the application code scope.
  • 构建纯REST/HTTP公开API且无gRPC需求。
  • 修改旧版
    .proto
    文件但无法引入新API版本(如
    api.v2
    )或确保向后兼容性。
  • 管理服务网格流量路由(如Istio/Linkerd),这属于应用代码范围之外的内容。

Step-by-Step Guide

分步指南

  1. Confirm Technical Context: Identify Go version, gRPC-Go version, and whether the project uses Buf or raw protoc.
  2. Confirm Requirements: Identify mTLS needs, load patterns (unary/streaming), SLOs, and message size limits.
  3. Plan Schema: Define package versioning (e.g.,
    api.v1
    ), resource types, and error mapping.
  4. Security Design: Implement mTLS for service-to-service authentication.
  5. Observability: Configure interceptors for tracing, metrics, and structured logging.
  6. Verification: Always run
    buf lint
    and breaking change checks before finalizing code generation.
Refer to
resources/implementation-playbook.md
for detailed patterns, code examples, and anti-patterns.
  1. 确认技术环境:确定Go版本、gRPC-Go版本,以及项目是否使用Buf或原生protoc。
  2. 确认需求:明确mTLS需求、负载模式(一元/流式)、服务水平目标(SLO)和消息大小限制。
  3. 规划Schema:定义包版本(如
    api.v1
    )、资源类型和错误映射。
  4. 安全设计:实现mTLS以进行服务间身份认证。
  5. 可观测性配置:配置拦截器以实现追踪、指标和结构化日志。
  6. 验证:在最终生成代码前,务必运行
    buf lint
    和破坏性变更检查。
详细的模式、代码示例和反模式请参考
resources/implementation-playbook.md

Examples

示例

Example 1: Defining a Service & Message (v1 API)

示例1:定义服务与消息(v1 API)

proto
syntax = "proto3";
package api.v1;
option go_package = "github.com/org/repo/gen/api/v1;apiv1";

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

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

message GetUserRequest {
  string id = 1;
}

message GetUserResponse {
  User user = 1;
}
proto
syntax = "proto3";
package api.v1;
option go_package = "github.com/org/repo/gen/api/v1;apiv1";

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

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

message GetUserRequest {
  string id = 1;
}

message GetUserResponse {
  User user = 1;
}

Best Practices

最佳实践

  • Do: Use Buf to standardize your toolchain and linting with
    buf.yaml
    and
    buf.gen.yaml
    .
  • Do: Always use semantic versioning in package paths (e.g.,
    package api.v1
    ).
  • Do: Enforce mTLS for all internal service-to-service communication.
  • Do: Handle
    ctx.Done()
    in all streaming handlers to prevent resource leaks.
  • Do: Map domain errors to standard gRPC status codes (e.g.,
    codes.NotFound
    ).
  • Don't: Return raw internal error strings or stack traces to gRPC clients.
  • Don't: Create a new
    grpc.ClientConn
    per request; always reuse connections.
  • 推荐:使用Buf标准化工具链,并通过
    buf.yaml
    buf.gen.yaml
    进行代码检查。
  • 推荐:始终在包路径中使用语义化版本(如
    package api.v1
    )。
  • 推荐:对所有内部服务间通信强制启用mTLS。
  • 推荐:在所有流式处理器中处理
    ctx.Done()
    以防止资源泄漏。
  • 推荐:将领域错误映射为标准gRPC状态码(如
    codes.NotFound
    )。
  • 不推荐:向gRPC客户端返回原始内部错误字符串或堆栈跟踪。
  • 不推荐:为每个请求创建新的
    grpc.ClientConn
    ;请始终复用连接。

Troubleshooting

故障排查

  • Error: Inconsistent Gen: If the generated code does not match the schema, run
    buf generate
    and verify the
    go_package
    option.
  • Error: Context Deadline: Check client timeouts and ensure the server is not blocking infinitely in streaming handlers.
  • Error: mTLS Handshake: Ensure the CA certificate is correctly added to the
    x509.CertPool
    on both client and server sides.
  • 错误:生成代码不一致:如果生成的代码与Schema不匹配,请运行
    buf generate
    并验证
    go_package
    配置。
  • 错误:上下文超时:检查客户端超时设置,并确保服务器在流式处理器中没有无限阻塞。
  • 错误:mTLS握手失败:确保CA证书已正确添加到客户端和服务器的
    x509.CertPool
    中。

Limitations

局限性

  • Does not cover service mesh traffic routing (Istio/Linkerd configuration).
  • Does not cover gRPC-Web or browser-based gRPC integration.
  • Assumes Go 1.21+ and gRPC-Go v1.60+; older versions may have different APIs (e.g.,
    grpc.Dial
    vs
    grpc.NewClient
    ).
  • Does not cover L7 gRPC-aware load balancer configuration (e.g., Envoy, NGINX).
  • Does not address Protobuf schema registry or large-scale schema governance beyond Buf lint.
  • 不涵盖服务网格流量路由(Istio/Linkerd配置)。
  • 不涵盖gRPC-Web或基于浏览器的gRPC集成。
  • 假设使用Go 1.21+和gRPC-Go v1.60+;旧版本可能有不同的API(如
    grpc.Dial
    vs
    grpc.NewClient
    )。
  • 不涵盖L7层gRPC感知负载均衡器配置(如Envoy、NGINX)。
  • 除Buf代码检查外,不涉及Protobuf Schema注册表或大规模Schema治理。

Resources

资源

Related Skills

相关技能

  • @golang-pro - General Go patterns and performance optimization outside the gRPC layer.
  • @go-concurrency-patterns - Advanced goroutine lifecycle management for streaming handlers.
  • @api-design-principles - Resource naming and versioning strategy before writing
    .proto
    files.
  • @docker-expert - Containerizing gRPC services and configuring TLS cert injection via Docker secrets.
  • @golang-pro:gRPC层之外的通用Go模式和性能优化。
  • @go-concurrency-patterns:用于流式处理器的高级goroutine生命周期管理。
  • @api-design-principles:编写
    .proto
    文件前的资源命名和版本化策略。
  • @docker-expert:将gRPC服务容器化,并通过Docker secrets配置TLS证书注入。