我目前正在学习围棋,我很感激大家对如何最好地减少重复代码数量的见解.
相关部件的文件夹 struct 如下:
.
├── http
│ ├── handlers
│ └── routes
├── models
│ └── dto
├── specifications
└── store
└── postgres
在我的specifications
文件夹中,我有两个‘store’界面:
type TaskStore interface {
CreateTask(ctx context.Context, input dto.TaskCreate) error
UpdateTask(ctx context.Context, id int, input dto.TaskUpdate) error
GetTask(ctx context.Context, id int) (dto.TaskResult, error)
ListTasks(ctx context.Context) ([]dto.TaskResult, error)
DeleteTask(ctx context.Context, id int) error
}
type TagStore interface {
CreateTag(ctx context.Context, input dto.TagCreate) error
RenameTag(ctx context.Context, id int, input dto.TagUpdate) error
ListTags(ctx context.Context) ([]dto.TagResult, error)
GetTag(ctx context.Context, id int) (dto.TagResult, error)
DeleteTag(ctx context.Context, id int) error
}
store/postgres
文件夹包含任务和标记的实现(存储库模式).
我看到的问题是:
在我的handlers
文件夹中,我有一个 struct ,它接受一个store 接口的输入:
type TaskHandler struct {
store specifications.TaskStore
}
func NewTaskHandler(store specifications.TaskStore) TaskHandler {
return TaskHandler{
store: store,
}
}
type TagHandler struct {
store specifications.TagStore
}
func NewTagHandler(store specifications.TagStore) TagHandler {
return TagHandler{
store: store,
}
}
这些处理程序包含将映射到api路径的方法:
func (h TaskHandler) List() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tasks, err := h.store.ListTasks(r.Context())
if err != nil {
log.Err(err).Msg("failed to retrieve tasks")
w.WriteHeader(http.StatusInternalServerError)
return
}
render.JSON(w, r, tasks)
}
}
func (h TagHandler) List() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tags, err := h.store.ListTags(r.Context())
if err != nil {
log.Err(err).Msg("failed to retrieve tags")
w.WriteHeader(http.StatusInternalServerError)
return
}
render.JSON(w, r, tags)
}
}
您将注意到,每个处理程序上的List
方法基本相同,只是每个store 使用的接口不同.
我怎样才能改变这一点,以减少重复的代码?
我最初认为我可以使用泛型来解决这个问题,比如:
type EntityStore[CreateDto any, UpdateDto any, ResultDto any] interface {
Create(ctx context.Context, input CreateDto) error
Update(ctx context.Context, id int, input UpdateDto) error
List(ctx context.Context) ([]ResultDto, error)
Get(ctx context.Context, id int) (ResultDto, error)
Delete(ctx context.Context, id int) error
}
但这将意味着将每种类型映射到处理程序中,我认为这不是一个实际的解决方案.
对于如何更好地映射我的DTO和接口,有什么建议吗?