【问题标题】:invalid receiver error when using Gin Gonic framework in Go在 Go 中使用 Gin Gonic 框架时出现无效的接收器错误
【发布时间】:2021-12-02 09:50:05
【问题描述】:

我正在尝试在基于 Gin 的 Web 服务器的路由中使用外部(非匿名)函数,如下所示:

package main

import (
    "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

我想知道如何在带有 gin gonic 的端点处理程序中使用匿名函数?到目前为止,我发现的所有文档都使用匿名函数。

谢谢!

【问题讨论】:

    标签: go go-gin


    【解决方案1】:

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

    你应该这样做:

    func Hi(c *gin.Context) {
    ...
    

    【讨论】:

      【解决方案2】:
      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)
      }
      

      【讨论】:

        猜你喜欢
        • 2017-08-03
        • 1970-01-01
        • 1970-01-01
        • 2015-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-06
        • 2017-08-09
        相关资源
        最近更新 更多