/
context.go
58 lines (45 loc) · 1.18 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
package meshauth
import (
"context"
"log/slog"
"time"
)
// AuthContext is a Context implementation holding auth info for a request.
type AuthContext struct {
MeshAuth *MeshAuth
// Parent
Context context.Context
// Slog
Logger *slog.Logger
Start time.Time
// Metrics/Tracing
// Auth info for this context
// Original IP and metadata.
}
func (a *AuthContext) Deadline() (deadline time.Time, ok bool) {
return a.Context.Deadline()
}
func (a *AuthContext) Done() <-chan struct{} {
return a.Context.Done()
}
func (a *AuthContext) Err() error {
return a.Context.Err()
}
// Value may return the AuthContext, if chained - or one of the fields.
// Otherwise will pass to parent.
func (a *AuthContext) Value(key any) any {
if key == ContextKey {
return a
}
return a.Context.Value(key)
}
const ContextKey = "meshAuth"
func (ma *MeshAuth) WithContext(ctx context.Context) context.Context {
if ctx == nil {
ctx = context.Background()
}
// WithValue is a struct holding the key and value (any), passing to next context.
// AuthContext holds multiple things in a map.
return &AuthContext{MeshAuth: ma, Context: ctx}
// instead of return context.WithValue(ctx, ContextKey, ma)
}