Senior
How are the models between layers organized?
sobes.tech AI
Answer from AI
In Go architecture, models between layers are usually organized through clear separation of responsibilities and data transfer.
- DTO (Data Transfer Objects) — structures used for transferring data between layers (e.g., between controller and service).
- Domain models — reflect business logic and rules, often located in the business logic layer.
- Persistence models — structures that correspond to database tables, used in the data access layer.
Organizing models between layers helps avoid tight coupling and facilitates testing and maintenance.
Example:
// Persistence model
type UserEntity struct {
ID int
Name string
Email string
}
// Domain model
type User struct {
ID int
Name string
Email string
}
// DTO for API transfer
type UserDTO struct {
Name string `json:"name"`
Email string `json:"email"`
}
// Conversion functions between models
func ToDomain(entity UserEntity) User {
return User{ID: entity.ID, Name: entity.Name, Email: entity.Email}
}
func ToDTO(user User) UserDTO {
return UserDTO{Name: user.Name, Email: user.Email}
}
Thus, each layer works with its own model, and conversions ensure architecture purity and layer independence.