Skip to content

fix(experimental): Functions for putting/getting an LDScopedClient from context.Context #305

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: v7
Choose a base branch
from

Conversation

aengelberg
Copy link
Contributor

@aengelberg aengelberg commented Aug 2, 2025

This PR introduces a few more functions to the main ld package. This will allow Go developers to easily pass around a scoped client to any logic that already takes a context.Context.

In particular, this will make writing HTTP middleware that establishes an LD context pretty easy. The middleware just needs to create a scoped client with the LD context it wants, then pass that scoped client into the http.Request's built-in Go context.

func LDScopedClientMiddleware(client *LDClient) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			scopedClient := NewScopedClient(client, ldcontext.New("user-key"))
			ctx := GoContextWithScopedClient(r.Context(), scopedClient)
			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}

func requestLogic(r *http.Request) {
	featureFlagEnabled := MustGetScopedClient(r.Context()).BoolVariation("my-flag", false)
	// use featureFlagEnabled...
}

@aengelberg aengelberg changed the title Functions for putting/getting an LDScopedClient from context.Context fix(experimental): Functions for putting/getting an LDScopedClient from context.Context Aug 11, 2025
@aengelberg aengelberg marked this pull request as ready for review August 11, 2025 22:43
@aengelberg aengelberg requested a review from a team as a code owner August 11, 2025 22:43
@keelerm84
Copy link
Member

bugbot run

panic("No scoped client found in context")
}
return client
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Nil Client in Context Causes Panic

MustGetScopedClient returns nil without panicking if a typed nil *LDScopedClient is stored in the context. This occurs because GetScopedClient returns ok=true for a typed nil value, and GoContextWithScopedClient allows storing nil. Consequently, callers receive nil instead of a panic, leading to a later nil dereference at the point of use and defeating the "must" contract.

Additional Locations (1)
Fix in Cursor Fix in Web

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants