@@ -8,15 +8,35 @@ import (
8
8
ld "github.com/launchdarkly/go-server-sdk/v7"
9
9
)
10
10
11
+ // RequestKeyFunc allows callers to override the request context key for the LDContext.
12
+ // Return (key, true) to use the provided key; return ("", false) to fall back to the default UUID key.
13
+ type RequestKeyFunc func (r * http.Request ) (string , bool )
14
+
11
15
// AddRequestScopedClient returns a net/http middleware that, for each incoming request,
12
16
// creates an LDScopedClient seeded with a `request`-kind LDContext populated with useful
13
17
// HTTP request attributes (e.g., method, path, host, userAgent), and stores it in the
14
18
// request's Go context. Downstream handlers can retrieve it via ld.GetScopedClient.
15
19
func AddRequestScopedClient (client * ld.LDClient ) func (next http.Handler ) http.Handler {
20
+ return AddRequestScopedClientWithKeyFn (client , nil )
21
+ }
22
+
23
+ // AddRequestScopedClientWithKeyFn is like AddRequestScopedClient, but allows providing a function to override
24
+ // the context key used for the `request`-kind LDContext. If the function returns ok=false or an empty key,
25
+ // a random UUID will be used.
26
+ func AddRequestScopedClientWithKeyFn (client * ld.LDClient , keyFn RequestKeyFunc ) func (next http.Handler ) http.Handler {
16
27
return func (next http.Handler ) http.Handler {
17
28
return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
18
- // Use a UUID to identify the request context key.
19
- requestKey := uuid .New ().String ()
29
+ // Determine request context key
30
+ requestKey := ""
31
+ if keyFn != nil {
32
+ if k , ok := keyFn (r ); ok && k != "" {
33
+ requestKey = k
34
+ }
35
+ }
36
+ if requestKey == "" {
37
+ requestKey = uuid .New ().String ()
38
+ }
39
+
20
40
b := ldcontext .NewBuilder (requestKey ).Kind ("request" ).Anonymous (true )
21
41
b .SetString ("method" , r .Method )
22
42
b .SetString ("host" , r .Host )
@@ -28,9 +48,6 @@ func AddRequestScopedClient(client *ld.LDClient) func(next http.Handler) http.Ha
28
48
}
29
49
b .SetString ("proto" , r .Proto )
30
50
b .SetString ("remoteAddr" , r .RemoteAddr )
31
- if rid := r .Header .Get ("X-Request-Id" ); rid != "" {
32
- b .SetString ("requestId" , rid )
33
- }
34
51
requestCtx := b .Build ()
35
52
36
53
scoped := ld .NewScopedClient (client , requestCtx )
0 commit comments