mirror of https://github.com/gofiber/fiber.git
add has method
parent
8f5aeedc39
commit
cbd2f09999
|
@ -130,6 +130,22 @@ if ratio, ok := app.State().GetFloat64("scalingFactor"); ok {
|
|||
}
|
||||
```
|
||||
|
||||
### Has
|
||||
|
||||
Has checks if a key exists in the State.
|
||||
|
||||
```go title="Signature"
|
||||
func (s *State) Has(key string) bool
|
||||
```
|
||||
|
||||
**Usage Example:**
|
||||
|
||||
```go
|
||||
if app.State().Has("appName") {
|
||||
fmt.Println("App Name is set.")
|
||||
}
|
||||
```
|
||||
|
||||
### Delete
|
||||
|
||||
Delete removes a key-value pair from the State.
|
||||
|
|
7
state.go
7
state.go
|
@ -84,6 +84,13 @@ func (s *State) GetFloat64(key string) (float64, bool) {
|
|||
return 0, false
|
||||
}
|
||||
|
||||
// Has checks if a key is present in the State.
|
||||
// It returns a boolean indicating if the key is present.
|
||||
func (s *State) Has(key string) bool {
|
||||
_, ok := s.Get(key)
|
||||
return ok
|
||||
}
|
||||
|
||||
// Delete removes a key-value pair from the State.
|
||||
func (s *State) Delete(key string) {
|
||||
s.dependencies.Delete(key)
|
||||
|
|
|
@ -120,6 +120,15 @@ func TestState_MustGet(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func TestState_Has(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
st := newState()
|
||||
|
||||
st.Set("key", "value")
|
||||
require.True(t, st.Has("key"))
|
||||
}
|
||||
|
||||
func TestState_Delete(t *testing.T) {
|
||||
t.Parallel()
|
||||
st := newState()
|
||||
|
@ -424,6 +433,22 @@ func BenchmarkState_GetStateWithDefault(b *testing.B) {
|
|||
}
|
||||
}
|
||||
|
||||
func BenchmarkState_Has(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
|
||||
st := newState()
|
||||
n := 1000
|
||||
// pre-populate the state
|
||||
for i := 0; i < n; i++ {
|
||||
st.Set("key"+strconv.Itoa(i), i)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
st.Has("key" + strconv.Itoa(i%n))
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkState_Delete(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
|
||||
|
|
Loading…
Reference in New Issue