Go Backend Microservices

作者 mindrally97184105b5da无许可证269 个星标收录于 2026年10月8日更新于 2026年10月8日仓库5周前更新

Go backend development best practices for microservices with clean architecture, observability, and production-ready patterns

AI 生成的概览

提供 Go 微服务开发规范,涵盖整洁架构、可观测性、测试与生产实践。

功能
给出面向微服务的 Go 后端开发约定,涉及整洁架构分层、项目目录结构、错误处理、上下文传递、可观测性、安全、测试、并发、文档以及 CI/CD。它只是纯说明性参考,产出的是指导建议而非代码或文件。
适用场景
适用于设计或评审 Go 微服务时,希望统一结构、错误处理、链路追踪、指标、日志和测试方面的约定。也适合为 Go 后端设定 lint 与 CI 规范。
运行要求
不附带任何脚本或工具,仅为说明性内容。若要落地这些建议,需要 Go 项目,并在相关部分使用 OpenTelemetry、Prometheus、golangci-lint 和测试容器。

Go Backend Development for Microservices

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

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

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

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:

Distributed Tracing

  • Add spans for significant operations
  • Propagate trace context across service boundaries
  • Include relevant attributes in spans

Metrics

  • Implement custom metrics for business operations
  • Use standard metric types (counters, gauges, histograms)
  • Export metrics in Prometheus format

Structured Logging

  • Use structured logging with consistent field names
  • Include trace IDs in log entries
  • Log at appropriate levels (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

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

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

Documentation

  • Document with GoDoc-style comments
  • Keep comments up to date with code changes
  • Document public APIs thoroughly
  • Include examples in documentation where helpful

CI/CD Integration

  • Maintain CI integration for linting and testing
  • Use golangci-lint for comprehensive linting
  • Run tests on every pull request
  • Include code coverage reporting

来源与署名

来源:mindrally/skills位于go-backend-microservices提交9718410

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架