登录
首页 >  Golang >  Go问答

如何调用go-gin中的接口函数?

来源:stackoverflow

时间:2024-03-30 22:30:32 348浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《如何调用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 实例作为接收器字段.

func ApplyRoutes(repo Repository, r *gin.RouterGroup) {
brand := r.Group("/brand") {
    brand.GET("/", func(ctx *gin.Context) {
        list(ctx, repo)
    })
}}

如果没有,这可能会起作用。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>