本文主要賞析一下go-ddd-samplegit
├── _sql ├── application ├── config ├── domain │ └── repository ├── infrastructure │ └── persistence │ └── testdata └── interfaces └── testdata
這裏分爲application、domain、infrastructure、interfaces四層
├── repository │ ├── mock_user.go │ └── user.go └── user.go
domain層定義了模型及repository接口,同時利用go generate生成repository的mock實現
// 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層來進行業務編排
└── persistence ├── main_test.go ├── testdata │ ├── schema.sql -> ../../../_sql/schema.sql │ └── users.yml ├── user_repository.go └── user_repository_test.go
infrastructure的persistence實現了domain層定義的repository接口
├── 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接口。github