@@ -2,12 +2,14 @@ package common
2
2
3
3
import (
4
4
"context"
5
+ "sync"
5
6
6
7
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
7
8
)
8
9
9
10
type ctxResourceDataKey struct {}
10
11
type ctxProviderMetaKey struct {}
12
+ type ctxDataKey struct {}
11
13
12
14
// NewResourceLifeCycleHandleFuncContext 创建一个资源生命周期处理方法上下文
13
15
func NewResourceLifeCycleHandleFuncContext (
@@ -19,6 +21,7 @@ func NewResourceLifeCycleHandleFuncContext(
19
21
ctx := context .WithValue (parent , LogIdKey , logID )
20
22
ctx = context .WithValue (ctx , ctxResourceDataKey {}, d )
21
23
ctx = context .WithValue (ctx , ctxProviderMetaKey {}, meta )
24
+ ctx = context .WithValue (ctx , ctxDataKey {}, & ContextData {})
22
25
return ctx
23
26
}
24
27
@@ -37,3 +40,77 @@ func ProviderMetaFromContext(ctx context.Context) interface{} {
37
40
}
38
41
return nil
39
42
}
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