Skip to content

Commit 92a82bd

Browse files
authored
Merge pull request #828 from Shinku-Chen/add-context-clone
add : Context Clone
2 parents ffdfd39 + e4c41a5 commit 92a82bd

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

context.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,15 @@ func (c *Context) ForEach(fn func(k string, v interface{}) interface{}) []interf
8585

8686
return ret
8787
}
88+
89+
// Clone clones context
90+
func (c *Context) Clone() *Context {
91+
c.lock.RLock()
92+
defer c.lock.RUnlock()
93+
newCtx := NewContext()
94+
c.ForEach(func(key string, value interface{}) interface{} {
95+
newCtx.Put(key, value)
96+
return nil
97+
})
98+
return newCtx
99+
}

context_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,24 @@ func TestContextIteration(t *testing.T) {
3737
}
3838
}
3939
}
40+
41+
func TestContextClone(t *testing.T) {
42+
ctxOrg := NewContext()
43+
for i := 0; i < 10; i++ {
44+
ctxOrg.Put(strconv.Itoa(i), i)
45+
}
46+
47+
ctx := ctxOrg.Clone()
48+
values := ctx.ForEach(func(k string, v interface{}) interface{} {
49+
return v.(int)
50+
})
51+
if len(values) != 10 {
52+
t.Fatal("fail to iterate context")
53+
}
54+
for _, i := range values {
55+
v := i.(int)
56+
if v != ctx.GetAny(strconv.Itoa(v)).(int) {
57+
t.Fatal("value not equal")
58+
}
59+
}
60+
}

0 commit comments

Comments
 (0)