[英]How to call Interface function in go-gin?
這是存儲庫 + controller
package brand
import (
"path/to/models"
"gorm.io/gorm"
"github.com/gin-gonic/gin"
)
type ResponseBrand struct {
Items []models.MasterBrand `json:"items"`
TotalCount int `json:"total"`
}
type Repository interface {
GetAll() (ResponseBrand, error)
}
type DBRepo struct {
db *gorm.DB
}
func (repo *DBRepo) GetAll() (ResponseBrand, error) {
var response ResponseBrand
var brands []models.MasterBrand
repo.db.Find(&brands)
response.Items = brands
response.TotalCount = len(brands)
return response, nil
}
func list(c *gin.Context) {
// this is an error
res, _ := Repository.GetAll()
}
這用於路由組
func ApplyRoutes(r *gin.RouterGroup) {
brand := r.Group("/brand") {
brand.GET("/", list)
}
}
我嘗試在我的項目中實現存儲庫,但仍然堅持在我們的 controller function列表中調用Repository.GetAll() 。 我為此使用杜松子酒和戈姆
接口只是類型為了實現該特定接口而必須具有的一組方法簽名。 所以你不能調用接口。
在您的示例代碼DBRepo
應該實現Repository
接口和 function list()
是一個 function 允許列出實現Repository
的任何類型的內容。 這樣做顯然list()
需要知道要列出的Repository
類類型的哪個實例 - 例如將其作為參數接收。 像這樣:
func list(ctx *gin.Context, repo Repository) {
// here call GetAll() which MUST exist on all types passed (otherwise they don't
// implement Repository interface
res, _ := repo.GetAll()
// ...
}
現在gin
將無法將修改后的列表作為路由器 function 因為這樣的簽名只是(ctx *gin.Context)
但您可以使用匿名 function 並將您的存儲庫感知list()
包裝在其中。
func ApplyRoutes(repo Repository, r *gin.RouterGroup) {
brand := r.Group("/brand") {
brand.GET("/", func(ctx *gin.Context) {
list(repo)
})
}
}
此外,您的ApplyRoutes()
function 需要知道應該在哪些存儲庫路由上運行 - 為了簡單起見,我在這里添加它作為參數,其他優雅的解決方案是將整個 controller 包裝在類型中並獲取Repository
實例作為接收器的字段。
func ApplyRoutes(repo Repository, r *gin.RouterGroup) {
brand := r.Group("/brand") {
brand.GET("/", func(ctx *gin.Context) {
list(ctx, repo)
})
}}
如果沒有,這可能會奏效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.