Skip to content

Commit

Permalink
fix(context): verify URL is Non-nil in initQueryCache() (#3969)
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianosela authored May 19, 2024
1 parent 4f339e6 commit e0d46de
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,7 @@ func (c *Context) QueryArray(key string) (values []string) {

func (c *Context) initQueryCache() {
if c.queryCache == nil {
if c.Request != nil {
if c.Request != nil && c.Request.URL != nil {
c.queryCache = c.Request.URL.Query()
} else {
c.queryCache = url.Values{}
Expand Down
43 changes: 43 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,49 @@ func TestContextQuery(t *testing.T) {
assert.Empty(t, c.PostForm("foo"))
}

func TestContextInitQueryCache(t *testing.T) {
validURL, err := url.Parse("https://github.com/gin-gonic/gin/pull/3969?key=value&otherkey=othervalue")
assert.Nil(t, err)

tests := []struct {
testName string
testContext *Context
expectedQueryCache url.Values
}{
{
testName: "queryCache should remain unchanged if already not nil",
testContext: &Context{
queryCache: url.Values{"a": []string{"b"}},
Request: &http.Request{URL: validURL}, // valid request for evidence that values weren't extracted
},
expectedQueryCache: url.Values{"a": []string{"b"}},
},
{
testName: "queryCache should be empty when Request is nil",
testContext: &Context{Request: nil}, // explicit nil for readability
expectedQueryCache: url.Values{},
},
{
testName: "queryCache should be empty when Request.URL is nil",
testContext: &Context{Request: &http.Request{URL: nil}}, // explicit nil for readability
expectedQueryCache: url.Values{},
},
{
testName: "queryCache should be populated when it not yet populated and Request + Request.URL are non nil",
testContext: &Context{Request: &http.Request{URL: validURL}}, // explicit nil for readability
expectedQueryCache: url.Values{"key": []string{"value"}, "otherkey": []string{"othervalue"}},
},
}

for _, test := range tests {
t.Run(test.testName, func(t *testing.T) {
test.testContext.initQueryCache()
assert.Equal(t, test.expectedQueryCache, test.testContext.queryCache)
})
}

}

func TestContextDefaultQueryOnEmptyRequest(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder()) // here c.Request == nil
assert.NotPanics(t, func() {
Expand Down

0 comments on commit e0d46de

Please sign in to comment.