Skip to content

Commit

Permalink
feat: a new userData API Remove (#1117)
Browse files Browse the repository at this point in the history
* feat:userData new api "delete"

* ctx api `remove`

* rename

* modify
  • Loading branch information
tylitianrui committed Oct 8, 2021
1 parent f307299 commit 7fdd526
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
10 changes: 10 additions & 0 deletions server.go
Expand Up @@ -698,6 +698,16 @@ func (ctx *RequestCtx) ResetUserValues() {
ctx.userValues.Reset()
}

// RemoveUserValue removes the given key and the value under it in ctx.
func (ctx *RequestCtx) RemoveUserValue(key string) {
ctx.userValues.Remove(key)
}

// RemoveUserValueBytes removes the given key and the value under it in ctx.
func (ctx *RequestCtx) RemoveUserValueBytes(key []byte) {
ctx.userValues.RemoveBytes(key)
}

type connTLSer interface {
Handshake() error
ConnectionState() tls.ConnectionState
Expand Down
21 changes: 21 additions & 0 deletions userdata.go
Expand Up @@ -21,6 +21,7 @@ func (d *userData) Set(key string, value interface{}) {
return
}
}

if value == nil {
return
}
Expand Down Expand Up @@ -72,3 +73,23 @@ func (d *userData) Reset() {
}
*d = (*d)[:0]
}

func (d *userData) Remove(key string) {
args := *d
n := len(args)
for i := 0; i < n; i++ {
kv := &args[i]
if string(kv.key) == key {
n--
args[i] = args[n]
args[n].value = nil
args = args[:n]
*d = args
return
}
}
}

func (d *userData) RemoveBytes(key []byte) {
d.Remove(b2s(key))
}
28 changes: 28 additions & 0 deletions userdata_test.go
Expand Up @@ -76,3 +76,31 @@ func (cv *closerValue) Close() error {
(*cv.closeCalls)++
return nil
}

func TestUserDataDelete(t *testing.T) {
t.Parallel()

var u userData

for i := 0; i < 10; i++ {
key := fmt.Sprintf("key_%d", i)
u.Set(key, i)
testUserDataGet(t, &u, []byte(key), i)
}

for i := 0; i < 10; i += 2 {
k := fmt.Sprintf("key_%d", i)
u.Remove(k)
if val := u.Get(k); val != nil {
t.Fatalf("unexpected key= %s, value =%v ,Expecting key= %s, value = nil", k, val, k)
}
kk := fmt.Sprintf("key_%d", i+1)
testUserDataGet(t, &u, []byte(kk), i+1)
}
for i := 0; i < 10; i++ {
key := fmt.Sprintf("key_new_%d", i)
u.Set(key, i)
testUserDataGet(t, &u, []byte(key), i)
}

}

0 comments on commit 7fdd526

Please sign in to comment.