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 TestReproduceNilPointerInGinContext(t *testing.T) {
    ctx := &gin.Context{}
    val := ctx.Value("my-key")
    fmt.Println(val)
}

Expectations

Expected to return value from context (if any).

Actual result

Nil pointer dereference.

Environment

  • go version: 1.18
  • gin version (or commit ref): v1.8.1
  • operating system: MacOs

Probably introduce with the commit https://github.com/gin-gonic/gin/commit/f197a8bae0c87e1b7cc2e32e399a40665a82f077

Comment From: ominidx

Bug in release v1.8.1 file context.go new condition added !c.engine.ContextWithFallback where c.engine is nil for empty gin.Context{}

if !c.engine.ContextWithFallback || c.Request == nil || c.Request.Context() == nil {
        return nil
    }

Comment From: ZackaryWelch

Probably the intended course of action is to create the context with CreateTestContextOnly and specify an engine.