Skip to content

Commit

Permalink
Prevent panic in Context.GetQuery() when there is no Request (#2412)
Browse files Browse the repository at this point in the history
Co-authored-by: thinkerou <thinkerou@gmail.com>
  • Loading branch information
pofl and thinkerou committed Aug 8, 2020
1 parent 30b5f7e commit 815e1ce
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
6 changes: 5 additions & 1 deletion context.go
Expand Up @@ -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{}
}
}
}

Expand Down
15 changes: 15 additions & 0 deletions context_test.go
Expand Up @@ -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")
Expand Down

0 comments on commit 815e1ce

Please sign in to comment.