Domain Interface
All domains must implement the simple interface fromapplication/domain.go:4:
The
GetRepository() method returns any because different domains have different repository types. The application only needs the repository reference to call its Migrations() method.Domain Structure
A typical domain aggregates four components:Component Breakdown
Repository - Data Access Layer
Repository - Data Access Layer
Handles all database operations for the domain:
- CRUD operations
- Complex queries
- Database migrations
- Transaction management
Service - Business Logic Layer
Service - Business Logic Layer
Implements domain business rules:
- Validation logic
- Orchestrates repository calls
- Coordinates with other domains
- Contains no HTTP or database code
HandlerGroup - HTTP API (Optional)
HandlerGroup - HTTP API (Optional)
Exposes HTTP endpoints for the domain:
- Route definitions
- Request/response handling
- Input validation
- Error mapping
Middleware - Request Processing (Optional)
Middleware - Request Processing (Optional)
Intercepts HTTP requests:
- Authentication/authorization
- Request validation
- Context enrichment
- Response modification
Real Example: Auth Domain
Theauth package provides a complete reference implementation. From auth/domain.go:7:
Auth Domain Constructor
Fromauth/domain.go:18, showing full domain initialization:
Creating a Domain
Follow these steps to create a new domain:1
Define your domain struct
Create a
domain.go file:2
Implement the Domain interface
Add the required method:
3
Create a constructor
Initialize all components:
4
Register with application
In your
main.go:Repository Pattern
Repositories handle all database operations:Service Pattern
Services implement business logic and orchestrate repository calls:Mounting Domain APIs
Mount your domain’s HTTP API to a server:/auth:
POST /auth/registerPOST /auth/loginGET /auth/me- etc.
Domains are self-contained. You can mount the same domain to multiple servers or use it in different applications.
Using Domain Middleware
Apply domain middleware to protect routes:auth/domain.go:27:
Domain Dependencies
Domains can depend on other domains via service interfaces:Testing Domains
Test each layer independently:Package Organization
Recommended file structure for a domain:Next Steps
HTTP Routing
Learn how to define domain APIs with HandlerGroup
Middleware
Create middleware for authentication and validation
Database
Set up repositories and migrations
Architecture
Understand the complete framework architecture