Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: a new userData API Remove #1117

Merged
merged 4 commits into from Oct 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
}

}