关于golang:聊聊godddsample

4次阅读

共计 1413 个字符,预计需要花费 4 分钟才能阅读完成。

本文次要赏析一下 go-ddd-sample

我的项目构造

├── _sql
├── application
├── config
├── domain
│   └── repository
├── infrastructure
│   └── persistence
│       └── testdata
└── interfaces
    └── testdata

这里分为 application、domain、infrastructure、interfaces 四层

domain

├── repository
│   ├── mock_user.go
│   └── user.go
└── user.go

domain 层定义了模型及 repository 接口,同时利用 go generate 生成 repository 的 mock 实现

application

// UserInteractor provides use-case
type UserInteractor struct {Repository repository.UserRepository}

// GetUser returns user
func (i UserInteractor) GetUser(ctx context.Context, id int) (*domain.User, error) {return i.Repository.Get(ctx, id)
}

// GetUsers returns user list
func (i UserInteractor) GetUsers(ctx context.Context) ([]*domain.User, error) {return i.Repository.GetAll(ctx)
}

// AddUser saves new user
func (i UserInteractor) AddUser(ctx context.Context, name string) error {u, err := domain.NewUser(name)
    if err != nil {return err}
    return i.Repository.Save(ctx, u)
}

applicatioin 层调用 domain 层来进行业务编排

infrastructure

└── persistence
    ├── main_test.go
    ├── testdata
    │   ├── schema.sql -> ../../../_sql/schema.sql
    │   └── users.yml
    ├── user_repository.go
    └── user_repository_test.go

infrastructure 的 persistence 实现了 domain 层定义的 repository 接口

interfaces

├── handler.go
├── handler_test.go
├── main_test.go
└── testdata
    ├── schema.sql -> ../../_sql/schema.sql
    └── users.yml

interfaces 基于 net/http 来提供 http 接口

小结

go-ddd-sample 分为 application、domain、infrastructure、interfaces 四层,其中 domain 定义 repository 接口,infrastructure 层实现该接口,application 层通过 domain 来编排业务逻辑,interfaces 层则基于 net/http 来提供 http 接口。

doc

  • go-ddd-sample
正文完
 0