-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
64 lines (53 loc) · 1.79 KB
/
context.go
File metadata and controls
64 lines (53 loc) · 1.79 KB
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
package hostlib
import (
"context"
)
// HostContext wraps a standard context.Context with host function-specific helpers.
// It provides access to the invoked function name and allows middleware to store
// request-scoped values without polluting the standard context.
type HostContext interface {
context.Context
// FunctionName returns the name of the host function being invoked.
FunctionName() string
// SetValue stores a request-scoped value. Unlike context.WithValue,
// this mutates the existing HostContext for performance.
SetValue(key, value any)
// GetValue retrieves a request-scoped value set by SetValue.
GetValue(key any) (value any, ok bool)
}
// hostContext is the concrete implementation of HostContext.
type hostContext struct {
context.Context
values map[any]any
funcName string
}
// NewHostContext creates a new HostContext wrapping the given context.
func NewHostContext(ctx context.Context, funcName string) HostContext {
return &hostContext{
Context: ctx,
funcName: funcName,
values: make(map[any]any),
}
}
// FunctionName returns the name of the host function being invoked.
func (c *hostContext) FunctionName() string {
return c.funcName
}
// SetValue stores a request-scoped value.
func (c *hostContext) SetValue(key, value any) {
c.values[key] = value
}
// GetValue retrieves a request-scoped value.
func (c *hostContext) GetValue(key any) (any, bool) {
v, ok := c.values[key]
return v, ok
}
// HostContextFrom extracts a HostContext from a context.Context.
// If the context is already a HostContext, it is returned directly.
// Otherwise, a new HostContext is created wrapping the given context.
func HostContextFrom(ctx context.Context, funcName string) HostContext {
if hc, ok := ctx.(HostContext); ok {
return hc
}
return NewHostContext(ctx, funcName)
}