Merge dee7eb410b47191fdecf58e838f4f77b384f1137 into f05f966a0824b1d302ee556183e2579c91954266

This commit is contained in:
Danial Gharib 2024-09-23 17:35:23 +08:00 committed by GitHub
commit f7139ea3db
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 15 additions and 4 deletions

View File

@ -6,6 +6,7 @@ package gin
import (
"errors"
"fmt"
"io"
"log"
"math"
@ -292,12 +293,21 @@ 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
}
return
} else {
err = fmt.Errorf("no value found for key '%s'", key)
return "", err
}
}
// GetBool returns the value associated with the key as a boolean.
func (c *Context) GetBool(key string) (b bool) {

View File

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