Skip to content

Commit 348e1be

Browse files
authored
feat: support storing temp data in ctx (#2884)
1 parent 44aece7 commit 348e1be

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

tencentcloud/common/context.go

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@ package common
22

33
import (
44
"context"
5+
"sync"
56

67
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
78
)
89

910
type ctxResourceDataKey struct{}
1011
type ctxProviderMetaKey struct{}
12+
type ctxDataKey struct{}
1113

1214
// NewResourceLifeCycleHandleFuncContext 创建一个资源生命周期处理方法上下文
1315
func NewResourceLifeCycleHandleFuncContext(
@@ -19,6 +21,7 @@ func NewResourceLifeCycleHandleFuncContext(
1921
ctx := context.WithValue(parent, LogIdKey, logID)
2022
ctx = context.WithValue(ctx, ctxResourceDataKey{}, d)
2123
ctx = context.WithValue(ctx, ctxProviderMetaKey{}, meta)
24+
ctx = context.WithValue(ctx, ctxDataKey{}, &ContextData{})
2225
return ctx
2326
}
2427

@@ -37,3 +40,77 @@ func ProviderMetaFromContext(ctx context.Context) interface{} {
3740
}
3841
return nil
3942
}
43+
44+
// DataFromContext 从上下文获取 data
45+
func DataFromContext(ctx context.Context) *ContextData {
46+
if data, ok := ctx.Value(ctxDataKey{}).(*ContextData); ok {
47+
return data
48+
}
49+
return nil
50+
}
51+
52+
// ContextData 上下文临时数据
53+
type ContextData struct {
54+
lock sync.RWMutex
55+
data map[string]interface{}
56+
}
57+
58+
// Set 设置值
59+
func (d *ContextData) Set(key string, v interface{}) {
60+
d.lock.Lock()
61+
defer d.lock.Unlock()
62+
if d.data == nil {
63+
d.data = make(map[string]interface{})
64+
}
65+
d.data[key] = v
66+
}
67+
68+
// Delete 删除值
69+
func (d *ContextData) Delete(key string) {
70+
d.lock.Lock()
71+
defer d.lock.Unlock()
72+
delete(d.data, key)
73+
}
74+
75+
// Get 获取键
76+
func (d *ContextData) Get(key string) interface{} {
77+
d.lock.RLock()
78+
defer d.lock.RUnlock()
79+
return d.data[key]
80+
}
81+
82+
// GetInt 获取 int 数据键
83+
func (d *ContextData) GetInt(key string) (ret int, ok bool) {
84+
ret, ok = d.Get(key).(int)
85+
return
86+
}
87+
88+
// GetUInt 获取 uint 数据键
89+
func (d *ContextData) GetUInt(key string) (ret uint, ok bool) {
90+
ret, ok = d.Get(key).(uint)
91+
return
92+
}
93+
94+
// GetInt64 获取 int64 数据键
95+
func (d *ContextData) GetInt64(key string) (ret int64, ok bool) {
96+
ret, ok = d.Get(key).(int64)
97+
return
98+
}
99+
100+
// GetUInt64 获取 uint64 数据键
101+
func (d *ContextData) GetUInt64(key string) (ret uint64, ok bool) {
102+
ret, ok = d.Get(key).(uint64)
103+
return
104+
}
105+
106+
// GetString 获取 string 数据键
107+
func (d *ContextData) GetString(key string) (ret string, ok bool) {
108+
ret, ok = d.Get(key).(string)
109+
return
110+
}
111+
112+
// GetBool 获取 bool 数据键
113+
func (d *ContextData) GetBool(key string) (ret bool, ok bool) {
114+
ret, ok = d.Get(key).(bool)
115+
return
116+
}

0 commit comments

Comments
 (0)