Description
In cases where we create a context with no engine (e.g. unit tests), it might lead to a nil pointer dereference.
How to reproduce
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
ctx := new(gin.Context)
fmt.Println(ctx.Done())
}
Actual result
goroutine 1 [running]:
github.com/gin-gonic/gin.(*Context).Done(0x1400004a768?)
/test/gin/go/pkg/mod/github.com/gin-gonic/gin@v1.9.0/context.go:1187 +0x1c
main.main()
/test/gin/main.go:11 +0x40
Environment
go version: 1.20.4
gin version: 1.9.1
operating system: MacOs
Comment From: jfabrizio26
@thinkerou
Comment From: axeloehrli
I have been experiencing the same issue and it is indeed fixed by https://github.com/gin-gonic/gin/pull/3664.
Comment From: yousifnimah
@jfabrizio26
The issue is that you are creating a new instance of gin.Context using ctx := new(gin.Context)
. However, the gin.Context struct is not intended to be instantiated directly.
The gin.Context
object is automatically created by the Gin framework when handling HTTP requests. You should not create it manually in your main function.
To fix the issue, you should define your route handlers within the main function, and the gin.Context
object will be created by Gin when a request is received.
Comment From: ossan-dev
@jfabrizio26 for unit tests, you should use something like this:
package main
import (
"fmt"
"net/http/httptest"
"github.com/gin-gonic/gin"
)
func main() {
ctx := gin.CreateTestContextOnly(httptest.NewRecorder(), gin.Default())
fmt.Println(ctx.Done())
ctx, _ = gin.CreateTestContext(httptest.NewRecorder())
fmt.Println(ctx.Done())
}
These functions are intended to be used for testing purposes so you should be good to go. Let me know
Comment From: yousifnimah
@jfabrizio26 for unit tests, you should use something like this:
```go package main
import ( "fmt" "net/http/httptest"
"github.com/gin-gonic/gin" )
func main() { ctx := gin.CreateTestContextOnly(httptest.NewRecorder(), gin.Default()) fmt.Println(ctx.Done()) ctx, _ = gin.CreateTestContext(httptest.NewRecorder()) fmt.Println(ctx.Done()) } ```
These functions are intended to be used for testing purposes so you should be good to go. Let me know
I tested it and it returns nil output