聊聊go-ddd-sample

本文详细解读了Go语言中的Domain-Driven Design (DDD)示例项目go-ddd-sample,涉及四层架构:应用层处理业务逻辑,领域层定义模型与接口,基础设施层实现数据持久化,接口层提供HTTP接口。重点介绍了repository的设计与mock实现,以及各层之间的交互方式。

本文主要赏析一下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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值