added proper errors for GetString() in context.go

This commit is contained in:
Danial 2023-07-09 21:43:18 +03:30
parent d4a64265f2
commit dee7eb410b
2 changed files with 15 additions and 4 deletions

View File

@ -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 {

View File

@ -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) {