mirror of https://github.com/gofiber/fiber.git
add GetStateWithDefault helper
parent
6fa12bbda8
commit
7f0afef988
10
state.go
10
state.go
|
@ -139,3 +139,13 @@ func MustGetState[T any](s *State, key string) T {
|
|||
|
||||
return dep
|
||||
}
|
||||
|
||||
// GetStateWithDefault retrieves a value from the State and casts it to the desired type, returning a default value in case the key is not found.
|
||||
func GetStateWithDefault[T any](s *State, key string, defaultVal T) T {
|
||||
dep, ok := GetState[T](s, key)
|
||||
if !ok {
|
||||
return defaultVal
|
||||
}
|
||||
|
||||
return dep
|
||||
}
|
||||
|
|
|
@ -233,6 +233,23 @@ func Test_MustGetStateGeneric(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func Test_GetStateWithDefault(t *testing.T) {
|
||||
t.Parallel()
|
||||
st := newState()
|
||||
|
||||
st.Set("flag", true)
|
||||
flag := GetStateWithDefault[bool](st, "flag", false)
|
||||
require.True(t, flag)
|
||||
|
||||
// mismatched type should return the default value
|
||||
str := GetStateWithDefault[string](st, "flag", "default")
|
||||
require.Equal(t, "default", str)
|
||||
|
||||
// missing key should return the default value
|
||||
flag = GetStateWithDefault[bool](st, "missing", false)
|
||||
require.False(t, flag)
|
||||
}
|
||||
|
||||
func BenchmarkState_Set(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
|
||||
|
@ -389,6 +406,24 @@ func BenchmarkState_MustGetStateGeneric(b *testing.B) {
|
|||
}
|
||||
}
|
||||
|
||||
func BenchmarkState_GetStateWithDefault(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
|
||||
st := newState()
|
||||
n := 1000
|
||||
// pre-populate the state
|
||||
for i := 0; i < n; i++ {
|
||||
key := "key" + strconv.Itoa(i)
|
||||
st.Set(key, i)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
key := "key" + strconv.Itoa(i%n)
|
||||
GetStateWithDefault[int](st, key, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkState_Delete(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
|
||||
|
|
Loading…
Reference in New Issue