-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathclient_context.go
More file actions
60 lines (51 loc) · 1.59 KB
/
client_context.go
File metadata and controls
60 lines (51 loc) · 1.59 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
package fastdns
import (
"context"
"net/netip"
)
type clientContextKey struct {
name string
}
// String returns the namespaced identifier for the client context key.
func (key *clientContextKey) String() string {
return "fastdns-" + key.name + "-context-key"
}
var clientOptionsContextKey any = &clientContextKey{"client-options"}
type clientOptionsContextValue struct {
prefix netip.Prefix
cookie string
padding uint16
}
func withClientOptions(ctx context.Context) (clientOptionsContextValue, bool) {
if v, ok := ctx.Value(clientOptionsContextKey).(*clientOptionsContextValue); ok {
return *v, true // copy-on-write
}
return clientOptionsContextValue{}, false
}
// WithClientSubnet returns a context carrying the client subnet prefix.
func WithClientSubnet(ctx context.Context, prefix netip.Prefix) context.Context {
v, ok := withClientOptions(ctx)
if ok && v.prefix == prefix {
return ctx
}
v.prefix = prefix
return context.WithValue(ctx, clientOptionsContextKey, &v)
}
// WithClientCookie returns a context carrying the client cookie value.
func WithClientCookie(ctx context.Context, cookie string) context.Context {
v, ok := withClientOptions(ctx)
if ok && v.cookie == cookie {
return ctx
}
v.cookie = cookie
return context.WithValue(ctx, clientOptionsContextKey, &v)
}
// WithClientPadding returns a context carrying the padded EDNS option.
func WithClientPadding(ctx context.Context, padding uint16) context.Context {
v, ok := withClientOptions(ctx)
if ok && v.padding == padding {
return ctx
}
v.padding = padding
return context.WithValue(ctx, clientOptionsContextKey, &v)
}