-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcontext.go
100 lines (77 loc) · 1.65 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package validator
import (
"context"
"github.com/raoptimus/validator.go/v2/set"
)
type Key uint8
const (
KeyDataSet Key = iota + 1
PreviousRulesErrored
)
type DataSet interface {
FieldValue(name string) (any, error)
FieldAliasName(name string) string
Name() set.Name
Data() any
}
type Context struct {
context.Context
ds DataSet
}
func NewContext(ctx context.Context) *Context {
return &Context{Context: ctx}
}
func (c *Context) Value(key any) any {
if key == KeyDataSet {
return c.ds
}
return c.Context.Value(key)
}
func (c *Context) withDataSet(ds DataSet) *Context {
cc := *c
cc.ds = ds
return &cc
}
func (c *Context) dataSet() (DataSet, bool) {
return c.ds, c.ds != nil
}
func DataSetFromContext[T DataSet](ctx *Context) (T, bool) {
if ds, ok := ctx.dataSet(); ok {
if dsT, ok2 := ds.(T); ok2 {
return dsT, true
}
}
var v T
return v, false
}
// todo: write funcs if context.Context interface
func withDataSet(ctx context.Context, ds DataSet) context.Context {
return NewContext(ctx).withDataSet(ds)
//return context.WithValue(ctx, KeyDataSet, ds)
}
func ExtractDataSet[T any](ctx context.Context) (T, bool) {
var v T
if ctx == nil {
return v, false
}
ds, ok := ctx.Value(KeyDataSet).(DataSet)
if !ok {
return v, false
}
if dst, ok := ds.(T); ok {
return dst, true
}
if dt, ok := ds.Data().(T); ok {
return dt, true
}
return v, false
}
func withPreviousRulesErrored(ctx context.Context) context.Context {
return context.WithValue(ctx, PreviousRulesErrored, true)
}
func previousRulesErrored(ctx context.Context) bool {
if y, ok := ctx.Value(PreviousRulesErrored).(bool); ok {
return y
}
return false
}