我目前正在学习 Go,我很感激人们对如何最好地减少重复代码量的见解。
相关部分的文件夹结构是这样的:
. ├── http │ ├── handlers │ └── routes ├── models │ └── dto ├── specifications └── store └── postgres
在我的 specations
文件夹中,我有 2 个“存储”接口:
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
文件夹中,我有一个结构体,它接受存储接口之一的输入:
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
方法基本相同,但每个商店使用的接口除外。
如何更改此设置以减少重复代码?
我最初认为我可以使用泛型来解决这个问题,例如:
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 和接口有什么建议吗?
正确答案
你可以有一个辅助函数
func ListHandler[T any](name string, lister func(ctx context.Context) ([]T, error)) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { list, err := lister(r.Context()) if err != nil { log.Err(err).Msg("failed to retrieve " + name) w.WriteHeader(http.StatusInternalServerError) return } render.JSON(w, r, list) } }
然后你就会有
func (h TaskHandler) List() http.HandlerFunc { return ListHandler("tasks", h.store.ListTasks) } func (h TagHandler) List() http.HandlerFunc { return ListHandler("tags", h.store.ListTags) }
以上是在 Go 中映射 DTO 时减少重复代码的数量的详细内容。更多信息请关注PHP中文网其他相关文章!

Golang和Python的主要区别在于并发模型、类型系统、性能和执行速度。1.Golang使用CSP模型,适用于高并发任务;Python依赖多线程和GIL,适合I/O密集型任务。2.Golang是静态类型,Python是动态类型。3.Golang编译型语言执行速度快,Python解释型语言开发速度快。

Golang通常比C 慢,但Golang在并发编程和开发效率上更具优势:1)Golang的垃圾回收和并发模型使其在高并发场景下表现出色;2)C 通过手动内存管理和硬件优化获得更高性能,但开发复杂度较高。

Golang在云计算和DevOps中的应用广泛,其优势在于简单性、高效性和并发编程能力。1)在云计算中,Golang通过goroutine和channel机制高效处理并发请求。2)在DevOps中,Golang的快速编译和跨平台特性使其成为自动化工具的首选。

Golang和C 在执行效率上的表现各有优势。1)Golang通过goroutine和垃圾回收提高效率,但可能引入暂停时间。2)C 通过手动内存管理和优化实现高性能,但开发者需处理内存泄漏等问题。选择时需考虑项目需求和团队技术栈。

Golang更适合高并发任务,而Python在灵活性上更有优势。1.Golang通过goroutine和channel高效处理并发。2.Python依赖threading和asyncio,受GIL影响,但提供多种并发方式。选择应基于具体需求。

Golang和C 在性能上的差异主要体现在内存管理、编译优化和运行时效率等方面。1)Golang的垃圾回收机制方便但可能影响性能,2)C 的手动内存管理和编译器优化在递归计算中表现更为高效。

selectgolangforhighpperformanceandcorrency,ifealforBackendServicesSandNetwork程序; selectpypypythonforrapiddevelopment,dataScience和machinelearningDuetoitsverserverserverserversator versator anderticality andextility andextentensivelibraries。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。 Golang以其并发模型和高效性能着称,Python则以简洁语法和丰富库生态系统着称。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

SublimeText3汉化版
中文版,非常好用

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具