Awesome-omni-skill go-microservice
This skill should be used when the user asks to "создать микросервис", "добавить домен", "имплементировать фичу", "использовать Uber FX", "создать репозиторий", "добавить gRPC endpoint", "добавить HTTP endpoint", "создать воркер", "составь план создания микросервиса", "использовать внутренние пакеты", "настроить kafka/redis/postgres/кафку/редис/постгрес", mentions "service_template", "shared", or needs guidance on Go microservice architecture, domain-driven design patterns, or backend development.
git clone https://github.com/diegosouzapw/awesome-omni-skill
T=$(mktemp -d) && git clone --depth=1 https://github.com/diegosouzapw/awesome-omni-skill "$T" && mkdir -p ~/.claude/skills && cp -r "$T/skills/design/go-microservice" ~/.claude/skills/diegosouzapw-awesome-omni-skill-go-microservice && rm -rf "$T"
skills/design/go-microservice/SKILL.mdGo Microservice Development
This skill provides guidance for creating and extending Go microservices using the internal service template and backend packages.
Overview
The microservice architecture follows Clean Architecture principles with Uber FX for dependency injection. All services share a common structure and use a set of internal infrastructure packages.
Architecture Overview
cmd/app/main.go # Entry point with signal handling config/config.go # Configuration with fx.Out pattern internal/ ├── app/app.go # fx bootstrap (CreateApp) ├── domain/ # Business logic (DDD) │ ├── fx.go # Domain modules aggregation │ └── {name}/ # Domain module │ ├── fx.go # Module registration │ ├── consts/ # Permission scopes │ ├── entities/ # Domain entities │ ├── dto/ # Request/Response objects │ ├── deps/ # Interface definitions │ ├── errors/ # Domain-specific errors │ ├── repository/ # Data access (postgres, http_clients) │ ├── usecase/ # Business logic │ ├── delivery/ # HTTP, gRPC, Kafka, RabbitMQ handlers │ └── workers/ # Background tasks └── infrastructure/ # Servers, clients, interceptors pkg/ # Local utilities (errors, httputil, ctxutil)
Domain Development Quick Guide
Creating New Domain - Checklist
1. [ ] Create directory: internal/domain/{name}/ 2. [ ] Create subdirectories: entities/, dto/, deps/, repository/postgres/, usecase/buissines/, delivery/http/, errors/ 3. [ ] Define entities in entities/entities.go 4. [ ] Define DTOs in dto/dto.go 5. [ ] Define interfaces in deps/dep.go 6. [ ] Implement repository in repository/postgres/repo.go 7. [ ] Implement usecase in usecase/buissines/uc.go 8. [ ] Implement HTTP handlers in delivery/http/handlers.go 9. [ ] Implement router in delivery/http/router.go 10. [ ] Create fx.Module in fx.go 11. [ ] Register module in internal/domain/fx.go 12. [ ] Validate: go test -run Test__CreateApp ./internal/app
For detailed file templates, consult
examples/new-domain-checklist.md.
Layer Rules Summary
| Layer | Key Rules | Example Tags/Patterns |
|---|---|---|
| Entities | Use db/json tags, typed constants for enums | |
| DTO | Separate Request/Response, use validate tags | |
| Deps | Interface-only, context.Context first | |
| Repository | Return interface, use NamedExec/Get/SelectContext | |
| Usecase | Inject via interfaces, return DTOs, validate | Inject deps, return dto |
| Delivery HTTP | fasthttp, httputil.WriteResponse | |
| Delivery gRPC | OnStart/OnStop lifecycle | |
| Workers | fx.Lifecycle, graceful shutdown via channels | |
For detailed patterns and code examples, consult
references/layer-patterns.md.
Internal Packages Quick Reference
Infrastructure Connectors
| Package | Purpose | FX Module | Key Interface |
|---|---|---|---|
| PostgreSQL | | |
| Redis/Sentinel | | |
| Kafka producer/consumer | Manual | , |
| RabbitMQ | Manual | , |
| HashiCorp Vault | | |
| S3 storage | | |
| ClickHouse | | |
Observability
| Package | Purpose | FX Module | Key Interface |
|---|---|---|---|
| Structured logging (zap) | | |
| OpenTelemetry tracing | | |
| Prometheus metrics | | |
| /healthz, /readyz probes | | - |
Utilities
| Package | Purpose |
|---|---|
| YAML/ENV configuration with validation |
| Event types for inter-service communication |
| Transactional Outbox pattern |
| In-memory cache (Cache, SnapshotCache, DeadlineCache) |
| Pagination primitives |
| gRPC access control via protobuf annotations |
| TLS certificates for gRPC |
| Wallet subscription streaming |
For detailed usage with code examples, consult
references/internal-packages.md.
FX Module Essentials
Module Registration Pattern
// internal/domain/{name}/fx.go var Module = fx.Module( "{name}", fx.Provide( postgres.NewRepository, buissines.NewUseCase, http.NewHandlers, http.NewRouter, ), )
Domain Aggregation
// internal/domain/fx.go var Module = fx.Module( "domain", order.Module, user.Module, // Add new domain modules here )
App Bootstrap
// internal/app/app.go func CreateApp() fx.Option { return fx.Options( loggerfx.LoggerFx, healthfx.HealthCheckFx, pgconnectorfx.PGConnectorFx, redisfx.RedisFx, domain.Module, infrastructure.Module, fx.Provide(config.Out, context.Background), healthfx.ReadinessProbeFX, ) }
Workers with Lifecycle
// internal/domain/{name}/workers/fx.go var Module = fx.Module( "{name}-workers", fx.Provide(NewWorker), fx.Invoke(registerLifecycle), ) func registerLifecycle(lc fx.Lifecycle, w *Worker) { lc.Append(fx.Hook{ OnStart: func(ctx context.Context) error { w.Start(ctx); return nil }, OnStop: func(ctx context.Context) error { w.Stop(); return nil }, }) }
For advanced patterns (fx.As, fx.Annotate, fx.In/Out), consult
references/fx-patterns.md.
Common Integration Scenarios
Adding HTTP Endpoint
- Add handler method to
delivery/http/handlers.go - Register route in
delivery/http/router.go - Add usecase method if needed
- Add repository method if needed
- Validate:
go test -run Test__CreateApp ./internal/app
Adding gRPC Endpoint
- Update proto definition
- Regenerate proto:
protoc --go_out=. --go-grpc_out=. *.proto - Implement handler in
delivery/grpc/handlers.go - Add usecase method if needed
- Validate fx graph
External HTTP Client Integration
- Create client:
repository/http_clients/{service}/client.go - Define interface in
deps/dep.go - Add config in
:config/config.goServiceName containers.RepositoryConfig `envPrefix:"SERVICE_NAME_"` - Register in fx.Module
Background Worker
- Create worker:
with ticker + done channelworkers/worker.go - Create fx module:
with lifecycle hooksworkers/fx.go - Register in domain fx.Module
New Configuration Field
- Add field to
with env/yaml/validate tagsconfig/config.go - Add to Result struct with
fx.Out - Return in
functionOut()
For detailed step-by-step scenarios, consult
references/template-structure.md.
Error Handling
Error Types and HTTP Codes
| Type | HTTP Code | Constructor |
|---|---|---|
| 400 | |
| 401 | |
| 403 | |
| 404 | |
| 409 | |
Domain Errors Pattern
// internal/domain/{name}/errors/errors.go package errors import pkgerrors "service/pkg/errors" var ( OrderNotFound = pkgerrors.NewNotFoundError("order not found") OrderAlreadyPaid = pkgerrors.NewConflictError("order already paid") InvalidOrderAmount = pkgerrors.NewValidationError("invalid amount") )
Handler Error Mapping
resp, err := h.uc.CreateOrder(ctx, &req) if err != nil { status, msg := h.mapper.MapErrorToHttp(err) httputil.WriteErrorResponse(ctx, msg, status, err) return } httputil.WriteResponse(ctx, resp)
Local Utilities (pkg/)
| Package | Purpose | Key Functions |
|---|---|---|
| Typed errors | , , |
| HTTP helpers | , , |
| Context helpers | , |
| Data generation | |
| Password hashing | , |
| Slice transforms | |
| Time formatting | (JSON-compatible) |
Context Keys (infrastructure/constants)
const ( UserIDContextKey = "user_id" MerchantIDContextKey = "merchant_id" SessionInfoContextKey = "session_info" ApiKeyInfoContextKey = "api_key_info" )
Commands
# Run application go run ./cmd/app # Run all tests go test ./... # Validate fx dependency graph go test -run Test__CreateApp ./internal/app # Generate swagger docs swag init -g ./cmd/app/main.go -o ./docs # Download dependencies go mod download
Additional Resources
Reference Files
For detailed patterns and techniques, consult:
- Complete file/folder structure with examplesreferences/template-structure.md
- Detailed package documentationreferences/internal-packages.md
- Advanced FX DI patternsreferences/fx-patterns.md
- Layer rules with code examplesreferences/layer-patterns.md
Example Files
Working examples in
examples/:
- Step-by-step domain creation with copy-paste codeexamples/new-domain-checklist.md