如何在go gin中调用接口函数?
这是存储库+控制器如何在go gin中调用接口函数?,go,interface,go-gin,Go,Interface,Go Gin,这是存储库+控制器 package brand import ( "path/to/models" "gorm.io/gorm" "github.com/gin-gonic/gin" ) type ResponseBrand struct { Items []models.MasterBrand `json:"items"` TotalCount int
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)
}
}
我尝试在项目中实现repository,但仍然坚持在控制器函数列表中调用repository.GetAll()。我对这个接口使用gin&gorm,接口只是一组方法签名,类型必须具有这些签名才能实现特定接口。所以不能调用接口 在您的示例中,code
DBRepo
应该实现Repository
接口,函数list()
是一个允许列出实现Repository
的任何类型的内容的函数。为此,显然list()
需要知道要列出类似存储库的类型的哪个实例,例如,将其作为参数接收。像这样:
func列表(ctx*gin.Context,repo存储库){
//这里调用GetAll(),它必须存在于传递的所有类型上(否则它们不存在)
//实现存储库接口
res,u:=repo.GetAll()
// ...
}
现在,gin
将无法将修改后的列表作为路由器函数,因为这样的签名只是(ctx*gin.Context)
,但您可以使用匿名函数并将存储库感知的列表()封装在其中
func ApplyRoutes(repo存储库,r*gin.RouterGroup){
品牌:=r.集团(“/品牌”){
brand.GET(“/”,func(ctx*gin.Context){
清单(回购)
})
}
}
另外,您的ApplyRoutes()
函数需要知道应该在哪些存储库路由上操作-为了简单起见,我在这里添加了它作为参数,其他优雅的解决方案是将整个控制器包装为类型,并获取存储库
实例作为接收方字段