mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-14 20:22:20 +08:00
Merge dee7eb410b47191fdecf58e838f4f77b384f1137 into f05f966a0824b1d302ee556183e2579c91954266
This commit is contained in:
commit
f7139ea3db
16
context.go
16
context.go
@ -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) {
|
||||
|
@ -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) {
|
||||
|
Loading…
x
Reference in New Issue
Block a user