Description

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    ctx := new(gin.Context)
    fmt.Println(ctx.Value("xx"))
}

Actual result

have a panic

goroutine 1 [running]:
github.com/gin-gonic/gin.(*Context).Value(0xc0001f7000, {0x1244ae0, 0x1304240})
        /test/gin/vendor/github.com/gin-gonic/gin/context.go:1198 +0xff
main.main()
        /test/gin/main.go:10 +0x38

fix

func (c *Context) Value(key any) any {
    if key == 0 {
        return c.Request
    }
    if key == ContextKey {
        return c
    }
    if keyAsString, ok := key.(string); ok {
        if val, exists := c.Get(keyAsString); exists {
            return val
        }
    }

         // Need to judge  c.engine is nil
    if c.engine == nil || !c.engine.ContextWithFallback || c.Request == nil || c.Request.Context() == nil {
        return nil
    }

    return c.Request.Context().Value(key)
}

Environment

  • gin version (or commit ref): v1.8.1

Comment From: snowdusk

Engine generates Context instance. Gin new a gin context bug Method allocateContext is unexported, so cannt new Context instance manually