我正在尝试在基于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) {
...
潇湘沐
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)
}
- 2 回答
- 0 关注
- 573 浏览
添加回答
举报
0/150
提交
取消
