为了账号安全,请及时绑定邮箱和手机立即绑定

在 Go 中使用 Gin Gonic 框架时出现无效的接收器错误

在 Go 中使用 Gin Gonic 框架时出现无效的接收器错误

Go
一只斗牛犬 2022-10-04 20:05:22
我正在尝试在基于Gin的Web服务器的路由中使用外部(非匿名)函数,如下所示:package mainimport (    "net/http"    "github.com/gin-gonic/gin")func main() {    router := gin.Default()    router.GET("/hi/", Hi)    router.Run(":8080")}func (c *gin.Context) Hi() {    c.String(http.StatusOK, "Hello")}但是我得到2个错误:./main.go:13:23: undefined: Hi./main.go:18:6: cannot define new methods on non-local type gin.Context我想知道如何在我的端点处理程序中使用匿名函数和杜松子酒gonic?到目前为止,我发现的所有文档都使用匿名函数。
查看完整描述

2 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

您只能为声明该类型的同一包中的类型定义新方法。也就是说,不能向 添加新方法。gin.Context


您应该执行以下操作:


func Hi(c *gin.Context) {

...


查看完整回答
反对 回复 2022-10-04
?
潇湘沐

TA贡献1816条经验 获得超6个赞

package main


import "github.com/gin-gonic/gin"


func main() {

    router := gin.Default()


    router.GET("/hi", hi)

    var n Node

    router.GET("/hello", n.hello)

    router.GET("/extra", func(ctx *gin.Context) {

        n.extra(ctx, "surprise~")

    })


    router.Run(":8080")

}


func hi(c *gin.Context) {

    c.String(200, "hi")

}


type Node struct{}


func (n Node) hello(c *gin.Context) {

    c.String(200, "world")

}


func (n Node) extra(c *gin.Context, data interface{}) {

    c.String(200, "%v", data)

}


查看完整回答
反对 回复 2022-10-04
  • 2 回答
  • 0 关注
  • 573 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号