From dee7eb410b47191fdecf58e838f4f77b384f1137 Mon Sep 17 00:00:00 2001 From: Danial Date: Sun, 9 Jul 2023 21:43:18 +0330 Subject: [PATCH] added proper errors for GetString() in context.go --- context.go | 16 +++++++++++++--- context_test.go | 3 ++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/context.go b/context.go index 420ff167..dd775ea6 100644 --- a/context.go +++ b/context.go @@ -6,6 +6,7 @@ package gin import ( "errors" + "fmt" "io" "log" "math" @@ -274,13 +275,22 @@ func (c *Context) MustGet(key string) any { } // GetString returns the value associated with the key as a string. -func (c *Context) GetString(key string) (s string) { +func (c *Context) GetString(key string) (s string, err error) { if val, ok := c.Get(key); ok && val != nil { - s, _ = val.(string) + if str, ok := val.(string); ok { + s = str + return s, nil + } else { + err = fmt.Errorf("value associated with key '%s' cannot be converted to a string", key) + return "", err + } + } else { + err = fmt.Errorf("no value found for key '%s'", key) + return "", err } - return } + // GetBool returns the value associated with the key as a boolean. func (c *Context) GetBool(key string) (b bool) { if val, ok := c.Get(key); ok && val != nil { diff --git a/context_test.go b/context_test.go index 70d47583..9d717576 100644 --- a/context_test.go +++ b/context_test.go @@ -229,7 +229,8 @@ func TestContextSetGetValues(t *testing.T) { func TestContextGetString(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("string", "this is a string") - assert.Equal(t, "this is a string", c.GetString("string")) + val, _ := c.GetString("string") + assert.Equal(t, "this is a string", val) } func TestContextSetGetBool(t *testing.T) {