go.mod for Microservice Projects
Best practices for structuring go.mod in microservice architectures. Manage shared libraries, API clients, and common dependencies across multiple Go services.
Detailed Explanation
go.mod in Microservice Architecture
Microservice projects present unique challenges for Go module management: shared dependencies, internal libraries, and the need for consistent dependency versions across services.
Typical Structure
platform/
├── user-service/
│ └── go.mod
├── order-service/
│ └── go.mod
├── api-gateway/
│ └── go.mod
└── pkg/
├── auth/
│ └── go.mod
├── logging/
│ └── go.mod
└── proto/
└── go.mod
Shared Library Management
Each shared library (pkg/auth, pkg/logging) has its own go.mod:
module github.com/myorg/platform/pkg/auth
go 1.22.0
require (
github.com/golang-jwt/jwt/v5 v5.2.0
google.golang.org/grpc v1.60.1
)
Services depend on shared libraries:
module github.com/myorg/platform/user-service
go 1.22.0
require (
github.com/myorg/platform/pkg/auth v0.5.0
github.com/myorg/platform/pkg/logging v0.3.0
github.com/myorg/platform/pkg/proto v0.8.0
github.com/gin-gonic/gin v1.9.1
google.golang.org/grpc v1.60.1
)
Common Dependencies
Microservices often share these dependency categories:
- gRPC:
google.golang.org/grpc,google.golang.org/protobuf - HTTP frameworks:
github.com/gin-gonic/gin,github.com/labstack/echo - Databases:
github.com/lib/pq,github.com/go-sql-driver/mysql - Observability:
go.opentelemetry.io/otel,github.com/prometheus/client_golang
Version Consistency
Keep gRPC and protobuf versions consistent across services to avoid compatibility issues:
// All services should use compatible gRPC versions
google.golang.org/grpc v1.60.1
google.golang.org/protobuf v1.31.0
Best Practices
- Pin shared library versions — use specific version tags, not branch refs
- Use go.work for local development — avoid replace directives in committed go.mod
- Automate dependency updates — use Dependabot or Renovate
- Consistent Go version — all services should use the same go directive
- Format go.mod — enforce consistent formatting across all services
Use Case
Teams building microservice platforms need consistent go.mod management across dozens of services. Using a formatter ensures all services follow the same go.mod conventions, making it easier to review dependency changes across the platform. Shared library version management is simplified when go.mod files are consistently formatted and easy to compare.