From 8cd66f7fa8939e4a47eb99132374e610e29cd338 Mon Sep 17 00:00:00 2001 From: Florian Polster Date: Mon, 15 Jun 2020 13:35:25 +0200 Subject: [PATCH 1/2] Prevent panic in Context.GetQuery() when there is no Request I have an endpoint that uses an optional query parameter via DefaultQuery(). In one unit test case I want to test the route with that parameter. I write that test as ```go w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) routeHandler(c) ``` And this panics when routeHandler() calls c.DefaultQuery() because c.Request == nil. --- context.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index a9458833ba..95b1807d72 100644 --- a/context.go +++ b/context.go @@ -416,7 +416,11 @@ func (c *Context) QueryArray(key string) []string { func (c *Context) initQueryCache() { if c.queryCache == nil { - c.queryCache = c.Request.URL.Query() + if c.Request != nil { + c.queryCache = c.Request.URL.Query() + } else { + c.queryCache = url.Values{} + } } } From 5186e18b8009877e2307c60652fa1865636dbd14 Mon Sep 17 00:00:00 2001 From: Florian Polster Date: Mon, 15 Jun 2020 21:40:02 +0200 Subject: [PATCH 2/2] Add unit tests to prevent panicing on missing Request --- context_test.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/context_test.go b/context_test.go index ce077bc691..bf63bab3c7 100644 --- a/context_test.go +++ b/context_test.go @@ -410,6 +410,21 @@ func TestContextQuery(t *testing.T) { assert.Empty(t, c.PostForm("foo")) } +func TestContextDefaultQueryOnEmptyRequest(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) // here c.Request == nil + assert.NotPanics(t, func() { + value, ok := c.GetQuery("NoKey") + assert.False(t, ok) + assert.Empty(t, value) + }) + assert.NotPanics(t, func() { + assert.Equal(t, "nada", c.DefaultQuery("NoKey", "nada")) + }) + assert.NotPanics(t, func() { + assert.Empty(t, c.Query("NoKey")) + }) +} + func TestContextQueryAndPostForm(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")