Skip to content

Commit f62449f

Browse files
committed
Separate AddRequestScopedClientWithKeyFn
1 parent 53e40b6 commit f62449f

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

ldmiddleware/http_middleware.go

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,35 @@ import (
88
ld "github.com/launchdarkly/go-server-sdk/v7"
99
)
1010

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+
1115
// AddRequestScopedClient returns a net/http middleware that, for each incoming request,
1216
// creates an LDScopedClient seeded with a `request`-kind LDContext populated with useful
1317
// HTTP request attributes (e.g., method, path, host, userAgent), and stores it in the
1418
// request's Go context. Downstream handlers can retrieve it via ld.GetScopedClient.
1519
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 {
1627
return func(next http.Handler) http.Handler {
1728
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+
2040
b := ldcontext.NewBuilder(requestKey).Kind("request").Anonymous(true)
2141
b.SetString("method", r.Method)
2242
b.SetString("host", r.Host)
@@ -28,9 +48,6 @@ func AddRequestScopedClient(client *ld.LDClient) func(next http.Handler) http.Ha
2848
}
2949
b.SetString("proto", r.Proto)
3050
b.SetString("remoteAddr", r.RemoteAddr)
31-
if rid := r.Header.Get("X-Request-Id"); rid != "" {
32-
b.SetString("requestId", rid)
33-
}
3451
requestCtx := b.Build()
3552

3653
scoped := ld.NewScopedClient(client, requestCtx)

0 commit comments

Comments
 (0)