Skip to content

Commit 4984b0f

Browse files
committed
Add request params to request context
1 parent 6d61262 commit 4984b0f

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

ldmiddleware/http_middleware.go

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,29 @@ import (
99
)
1010

1111
// AddRequestScopedClient returns a net/http middleware that, for each incoming request,
12-
// creates an LDScopedClient seeded with a `request`-kind LDContext and stores it in the
12+
// creates an LDScopedClient seeded with a `request`-kind LDContext populated with useful
13+
// HTTP request attributes (e.g., method, path, host, userAgent), and stores it in the
1314
// request's Go context. Downstream handlers can retrieve it via ld.GetScopedClient.
1415
func AddRequestScopedClient(client *ld.LDClient) func(next http.Handler) http.Handler {
1516
return func(next http.Handler) http.Handler {
1617
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1718
// Use a UUID to identify the request context key.
1819
requestKey := uuid.New().String()
19-
requestCtx := ldcontext.NewWithKind("request", requestKey)
20+
b := ldcontext.NewBuilder(requestKey).Kind("request").Anonymous(true)
21+
b.SetString("method", r.Method)
22+
b.SetString("host", r.Host)
23+
b.SetString("userAgent", r.UserAgent())
24+
if r.URL != nil {
25+
b.SetString("path", r.URL.Path)
26+
b.SetString("scheme", r.URL.Scheme)
27+
b.SetString("query", r.URL.RawQuery)
28+
}
29+
b.SetString("proto", r.Proto)
30+
b.SetString("remoteAddr", r.RemoteAddr)
31+
if rid := r.Header.Get("X-Request-Id"); rid != "" {
32+
b.SetString("requestId", rid)
33+
}
34+
requestCtx := b.Build()
2035

2136
scoped := ld.NewScopedClient(client, requestCtx)
2237
ctxWithScoped := ld.GoContextWithScopedClient(r.Context(), scoped)

0 commit comments

Comments
 (0)