When I use ginCtx.ClientIP(), my program got panic. I figured out that in that context, engine is <nil>.
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)
}
I expected that my program must be run correctly without be panicked. And it would print 127.0.0.1.
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]
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
Most helpful comment
I fixed it by using the code below instead. I realized that main cause is
requestHeadernotengineis<nil>.