如何解决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 `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)
}
}
我尝试在我的项目中实现存储库,但仍然坚持在我们的控制器函数 list 中调用 Repository.GetAll()。我为此使用杜松子酒和戈姆
解决方法
接口只是类型必须具有的一组方法签名,以便实现该特定接口。所以你不能调用接口。
在您的示例代码中,DBRepo
应该实现 Repository
接口,而函数 list()
是一个允许列出实现 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
将无法将修改后的列表作为路由器函数,因为它的签名只是 (ctx *gin.Context)
但您可以使用匿名函数并包装您的存储库感知 list()
在里面。
func ApplyRoutes(repo Repository,r *gin.RouterGroup) {
brand := r.Group("/brand") {
brand.GET("/",func(ctx *gin.Context) {
list(repo)
})
}
}
此外,您的 ApplyRoutes()
函数需要知道应该在哪些 Repository 路由上运行 - 为了简单起见,我在此处添加了它作为参数,其他优雅的解决方案是将整个控制器包装在类型中并获取 Repository
实例作为接收器的字段。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。