在 Go 中對應 DTO 時減少重複程式碼的數量
我目前正在學習 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中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

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

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

Go語言中用於浮點數運算的庫介紹在Go語言(也稱為Golang)中,進行浮點數的加減乘除運算時,如何確保精度是�...

Go爬蟲Colly中的Queue線程問題探討在使用Go語言的Colly爬蟲庫時,開發者常常會遇到關於線程和請求隊列的問題。 �...

後端學習路徑:從前端轉型到後端的探索之旅作為一名從前端開發轉型的後端初學者,你已經有了nodejs的基礎,...

本文討論了通過go.mod,涵蓋規範,更新和衝突解決方案管理GO模塊依賴關係。它強調了最佳實踐,例如語義版本控制和定期更新。

本文介紹在Debian系統下監控PostgreSQL數據庫的多種方法和工具,助您全面掌握數據庫性能監控。一、利用PostgreSQL內置監控視圖PostgreSQL自身提供多個視圖用於監控數據庫活動:pg_stat_activity:實時展現數據庫活動,包括連接、查詢和事務等信息。 pg_stat_replication:監控複製狀態,尤其適用於流複製集群。 pg_stat_database:提供數據庫統計信息,例如數據庫大小、事務提交/回滾次數等關鍵指標。二、借助日誌分析工具pgBadg
