go-backend-microservices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Go Backend Development for Microservices

Go微服务后端开发

Core Principles

核心原则

  • Apply Clean Architecture with clear separation into handlers, services, repositories, and domain models
  • Prioritize interface-driven development with explicit dependency injection
  • Write short, focused functions with a single responsibility
  • Ensure safe use of goroutines, and guard shared state with channels or sync primitives
  • 应用整洁架构,清晰划分为处理器(handlers)、服务(services)、仓库(repositories)和领域模型
  • 优先采用接口驱动开发,明确依赖注入
  • 编写简短、聚焦且单一职责的函数
  • 安全使用goroutines,通过通道(channels)或同步原语保护共享状态

Project Structure

项目结构

Maintain modular project structure with clear directories:
project/
├── cmd/           # Application entry points
├── internal/      # Private application code
├── pkg/           # Public library code
├── api/           # API definitions (OpenAPI, protobuf)
├── configs/       # Configuration files
└── test/          # Additional test utilities
保持模块化项目结构,目录清晰:
project/
├── cmd/           # 应用入口点
├── internal/      # 私有应用代码
├── pkg/           # 公共库代码
├── api/           # API定义(OpenAPI、protobuf)
├── configs/       # 配置文件
└── test/          # 额外测试工具

Error Handling

错误处理

  • Always check and handle errors explicitly
  • Use wrapped errors for traceability:
    fmt.Errorf("context: %w", err)
  • Create custom error types for domain-specific errors
  • Return errors up the call stack with appropriate context
  • Log errors at the appropriate level with sufficient context
  • 始终显式检查并处理错误
  • 使用包装错误以实现可追溯性:
    fmt.Errorf("context: %w", err)
  • 针对领域特定错误创建自定义错误类型
  • 在调用栈中向上返回带有适当上下文的错误
  • 在适当级别记录错误并提供足够上下文

Context Propagation

上下文传递

  • Use context propagation for request-scoped values, deadlines, and cancellations
  • Pass context as the first parameter to functions
  • Respect context cancellation in long-running operations
  • Set appropriate timeouts for external calls
  • 使用上下文传递请求作用域的值、截止时间和取消信号
  • 将上下文作为函数的第一个参数传递
  • 在长时间运行的操作中尊重上下文取消
  • 为外部调用设置适当的超时时间

Observability

可观测性

Implement OpenTelemetry for comprehensive observability:
使用OpenTelemetry实现全面可观测性:

Distributed Tracing

分布式追踪

  • Add spans for significant operations
  • Propagate trace context across service boundaries
  • Include relevant attributes in spans
  • 为重要操作添加追踪跨度(spans)
  • 在服务边界间传递追踪上下文
  • 在跨度中包含相关属性

Metrics

指标

  • Implement custom metrics for business operations
  • Use standard metric types (counters, gauges, histograms)
  • Export metrics in Prometheus format
  • 为业务操作实现自定义指标
  • 使用标准指标类型(计数器、仪表盘、直方图)
  • 以Prometheus格式导出指标

Structured Logging

结构化日志

  • Use structured logging with consistent field names
  • Include trace IDs in log entries
  • Log at appropriate levels (debug, info, warn, error)
  • 使用具有一致字段名的结构化日志
  • 在日志条目中包含追踪ID
  • 在适当级别记录日志(debug、info、warn、error)

Security

安全

  • Apply input validation rigorously on all external inputs
  • Use secure defaults for JWT tokens and cookies
  • Implement proper authentication and authorization
  • Sanitize data before logging to avoid leaking sensitive information
  • Use prepared statements for database queries
  • 对所有外部输入严格执行输入验证
  • 为JWT令牌和Cookie使用安全默认值
  • 实现正确的身份认证与授权
  • 在记录日志前清理数据,避免泄露敏感信息
  • 对数据库查询使用预编译语句

Testing

测试

Unit Tests

单元测试

  • Write table-driven unit tests with adequate coverage
  • Use parallel test execution where safe
  • Mock external dependencies using interfaces
  • Focus on testing business logic
  • 编写表驱动的单元测试,保证足够覆盖率
  • 在安全场景下使用并行测试执行
  • 使用接口模拟外部依赖
  • 聚焦于业务逻辑测试

Integration Tests

集成测试

  • Separate integration tests from unit tests
  • Use test containers for database and service dependencies
  • Test actual API endpoints and responses
  • 将集成测试与单元测试分离
  • 使用测试容器处理数据库和服务依赖
  • 测试实际API端点和响应

Concurrency

并发

  • Use goroutines appropriately for concurrent operations
  • Guard shared state with channels or sync primitives
  • Implement proper graceful shutdown
  • Use worker pools for bounded concurrency
  • 合理使用goroutines进行并发操作
  • 通过通道或同步原语保护共享状态
  • 实现正确的优雅停机
  • 使用工作池实现有界并发

Documentation

文档

  • Document with GoDoc-style comments
  • Keep comments up to date with code changes
  • Document public APIs thoroughly
  • Include examples in documentation where helpful
  • 使用GoDoc风格的注释编写文档
  • 保持注释与代码变更同步更新
  • 全面记录公共API
  • 在有帮助的地方为文档添加示例

CI/CD Integration

CI/CD集成

  • Maintain CI integration for linting and testing
  • Use golangci-lint for comprehensive linting
  • Run tests on every pull request
  • Include code coverage reporting
  • 持续集成(CI)集成代码检查和测试
  • 使用golangci-lint进行全面代码检查
  • 在每个拉取请求(PR)上运行测试
  • 包含代码覆盖率报告