Gin: Context was responded from `CreateTestContext` do not have engine

Created on 3 Jul 2020  路  2Comments  路  Source: gin-gonic/gin

Description

When I use ginCtx.ClientIP(), my program got panic. I figured out that in that context, engine is <nil>.

How to reproduce

package main

import (
    "fmt"
    "net/http/httptest"
    "testing"
    "github.com/stretchr/testify/require"
    "github.com/gin-gonic/gin"
)

func TestContext(t *testing.T) {
    w := httptest.NewRecorder()
    ginCtx, engine := gin.CreateTestContext(w)
    ginCtx.Header("X-Forwarded-For", "127.0.0.1")

    fmt.Println(ginCtx.ClientIP())
    require.Equal(t, true, engine.ForwardedByClientIP)
}

Expectations

I expected that my program must be run correctly without be panicked. And it would print 127.0.0.1.

Actual result

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
    panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x38 pc=0x15390d6]

Environment

  • go version: go version go1.14.3 darwin/amd64
  • gin version: github.com/gin-gonic/gin v1.3.0
  • operating system: macOS Catalina 10.15.5. Macbook Pro 13-inch, 2017.

Most helpful comment

I fixed it by using the code below instead. I realized that main cause is requestHeader not engine is <nil>.

w := httptest.NewRecorder()
ginCtx, _ := gin.CreateTestContext(w)
ginCtx.Request, _ = http.NewRequest("POST", "/", nil)
ginCtx.Request.Header.Set("X-Forwarded-For", "127.0.0.1")

All 2 comments

I fixed it by using the code below instead. I realized that main cause is requestHeader not engine is <nil>.

w := httptest.NewRecorder()
ginCtx, _ := gin.CreateTestContext(w)
ginCtx.Request, _ = http.NewRequest("POST", "/", nil)
ginCtx.Request.Header.Set("X-Forwarded-For", "127.0.0.1")

Lol

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iiinsomnia picture iiinsomnia  路  3Comments

wangcn picture wangcn  路  3Comments

lilee picture lilee  路  3Comments

mastrolinux picture mastrolinux  路  3Comments

nxvl picture nxvl  路  3Comments