Home > database >  invalid receiver error when using Gin Gonic framework in Go
invalid receiver error when using Gin Gonic framework in Go

Time:10-14

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!

CodePudding user response:

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) {
...
  • Related