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

huangapple go评论79阅读模式
英文:

invalid receiver error when using Gin Gonic framework in Go

问题

我正在尝试在基于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 Hi(c *gin.Context) {

	c.String(http.StatusOK, "Hello")
}

但是我遇到了两个错误:

./main.go:13:23: undefined: Hi
./main.go:18:6: cannot define new methods on non-local type gin.Context

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

谢谢!

英文:

I am trying to use an external (non anonymous) function in the routing of my Gin based web server as shown below:

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")
}

But I get 2 errors:

./main.go:13:23: undefined: Hi
./main.go:18:6: cannot define new methods on non-local type gin.Context

I am wondering how I can use anonymous functions in my endpoint handlers with gin gonic? All the documentation I've found so far uses anonymous functions.

Thanks!

答案1

得分: 1

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

你应该这样做:

func Hi(c *gin.Context) {
...
英文:

You can only define a new method for a type in the same package declaring that type. That is, you cannot add a new method to gin.Context.

You should do:

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

答案2

得分: 1

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, "惊喜~")
	})

	router.Run(":8080")
}

func hi(c *gin.Context) {
	c.String(200, "你好")
}

type Node struct{}

func (n Node) hello(c *gin.Context) {
	c.String(200, "世界")
}

func (n Node) extra(c *gin.Context, data interface{}) {
	c.String(200, "%v", data)
}
英文:
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)
}

huangapple
  • 本文由 发表于 2021年10月14日 07:49:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/69563568.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定