gin icon indicating copy to clipboard operation
gin copied to clipboard

🐛 Nil pointer dereference when context has no engine defined

Open jbleduigou opened this issue 1 year ago • 1 comments

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

jbleduigou avatar Jun 08 '22 12:06 jbleduigou

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
	}

ominidx avatar Jun 09 '22 12:06 ominidx

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

ZackaryWelch avatar Feb 20 '23 21:02 ZackaryWelch