diff --git a/context.go b/context.go index 1f356515..63ea0678 100644 --- a/context.go +++ b/context.go @@ -6,6 +6,7 @@ package gin import ( "errors" + "fmt" "io" "log" "math" @@ -292,13 +293,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 211fbb1b..2cbb889e 100644 --- a/context_test.go +++ b/context_test.go @@ -237,7 +237,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) {