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.
I fixed it by using the code below instead. I realized that main cause is
requestHeader
notengine
is<nil>
.