From 36b0dede4b8c4a67d92c4107cebc5a068364321d Mon Sep 17 00:00:00 2001 From: 51pwn <18223385+hktalent@users.noreply.github.com> Date: Mon, 13 May 2024 14:55:41 +0800 Subject: [PATCH] fix(context): check handler is nil (#3413) * fixed #3404 2022-11-23 * up 2022-11-23 * refactor: refactor context handling and nil checks - Refactor nil checks to improve readability in `context.go` - Modify the control flow in `HandlerNames` and `Next` methods to continue on nil values before appending or invoking handlers in `context.go` Signed-off-by: Bo-Yi Wu * test: refactor context_test.go for clarity and efficiency - Insert a `nil` value into the `HandlersChain` array in `context_test.go` - Remove empty test functions in `context_test.go` Signed-off-by: Bo-Yi Wu --------- Signed-off-by: Bo-Yi Wu Co-authored-by: Bo-Yi Wu --- context.go | 6 ++++++ context_test.go | 5 ++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/context.go b/context.go index 35250667..cd2645a9 100644 --- a/context.go +++ b/context.go @@ -152,6 +152,9 @@ func (c *Context) HandlerName() string { func (c *Context) HandlerNames() []string { hn := make([]string, 0, len(c.handlers)) for _, val := range c.handlers { + if val == nil { + continue + } hn = append(hn, nameOfFunction(val)) } return hn @@ -182,6 +185,9 @@ func (c *Context) FullPath() string { func (c *Context) Next() { c.index++ for c.index < int8(len(c.handlers)) { + if c.handlers[c.index] == nil { + continue + } c.handlers[c.index](c) c.index++ } diff --git a/context_test.go b/context_test.go index 36d6e34a..517f73e2 100644 --- a/context_test.go +++ b/context_test.go @@ -362,7 +362,7 @@ func TestContextHandlerName(t *testing.T) { func TestContextHandlerNames(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) - c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest, func(c *Context) {}, handlerNameTest2} + c.handlers = HandlersChain{func(c *Context) {}, nil, handlerNameTest, func(c *Context) {}, handlerNameTest2} names := c.HandlerNames() @@ -1671,7 +1671,6 @@ func TestContextBindWithXML(t *testing.T) { } func TestContextBindPlain(t *testing.T) { - // string w := httptest.NewRecorder() c, _ := CreateTestContext(w) @@ -1863,7 +1862,6 @@ func TestContextShouldBindPlain(t *testing.T) { assert.NoError(t, c.ShouldBindPlain(&bs)) assert.Equal(t, []byte("test []byte"), bs) assert.Equal(t, 0, w.Body.Len()) - } func TestContextShouldBindHeader(t *testing.T) { @@ -2371,6 +2369,7 @@ func TestContextShouldBindBodyWithPlain(t *testing.T) { } } } + func TestContextGolangContext(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))