Skip to content

实践 1

结构

/internal/user/
├── domain/              ← 核心(最重要)
│   ├── user.go         ← Entity(含行为)
│   ├── role.go         ← 领域对象
│   └── repository.go   ← 仓储接口(interface)

├── application/        ← 用例层(流程编排)
│   ├── service.go
│   └── command.go      ← DTO(入参)

├── infrastructure/     ← 技术实现
│   └── repo_impl.go    ← DB 实现

└── interfaces/         ← 对外(HTTP / RPC)
    └── handler.go
/user/
├── user.go          ← domain(先不拆)
├── service.go       ← application
├── repo.go          ← interface + impl(先合并)
├── handler.go       ← http

handler.go

handler.go 很薄,不能泄漏业务逻辑。

Deps 最小化依赖

go
// 每个 module 有自己的 Deps,最小化依赖
type Deps struct {
    DB    *gorm.DB
    Cache CacheClient
}

type Module struct {
    Handler *Handler
}

func (m *Module) Register(r *gin.Engine) {
    m.Handler.Register(r)
}

func NewModule(deps Deps) *Module {
    repo := NewRepo(deps.DB)
    service := NewService(repo, deps.Cache)
    handler := NewHandler(service)

    return &Module{
        Handler: handler,
    }
}