@@ -39,6 +39,17 @@ type Client struct {
3939 errorHandler func (handler * FlagsmithAPIError )
4040}
4141
42+ // Returns context with provided EvaluationContext instance set.
43+ func WithEvaluationContext (ctx context.Context , ec EvaluationContext ) context.Context {
44+ return context .WithValue (ctx , contextKeyEvaluationContext , ec )
45+ }
46+
47+ // Retrieve EvaluationContext instance from context.
48+ func GetEvaluationContextFromCtx (ctx context.Context ) (ec EvaluationContext , ok bool ) {
49+ ec , ok = ctx .Value (contextKeyEvaluationContext ).(EvaluationContext )
50+ return ec , ok
51+ }
52+
4253// NewClient creates instance of Client with given configuration.
4354func NewClient (apiKey string , options ... Option ) * Client {
4455 c := & Client {
@@ -104,7 +115,7 @@ func NewClient(apiKey string, options ...Option) *Client {
104115// * `EvaluationContext.Feature` is not yet supported.
105116func (c * Client ) GetFlags (ctx context.Context , ec * EvaluationContext ) (f Flags , err error ) {
106117 if ec != nil {
107- ctx = context . WithValue (ctx , contextKeyEvaluationContext , ec )
118+ ctx = WithEvaluationContext (ctx , * ec )
108119 if ec .Identity != nil {
109120 return c .GetIdentityFlags (ctx , ec .Identity .Identifier , mapIdentityEvaluationContextToTraits (* ec .Identity ))
110121 }
@@ -212,9 +223,9 @@ func (c *Client) BulkIdentify(ctx context.Context, batch []*IdentityTraits) erro
212223// Will return an error in case of failure or unexpected response.
213224func (c * Client ) GetEnvironmentFlagsFromAPI (ctx context.Context ) (Flags , error ) {
214225 req := c .client .NewRequest ()
215- maybeEc := ctx . Value ( contextKeyEvaluationContext )
216- if maybeEc != nil {
217- envCtx := maybeEc .( * EvaluationContext ) .Environment
226+ ec , ok := GetEvaluationContextFromCtx ( ctx )
227+ if ok {
228+ envCtx := ec .Environment
218229 if envCtx != nil {
219230 req .SetHeader (EnvironmentKeyHeader , envCtx .APIKey )
220231 }
@@ -243,9 +254,8 @@ func (c *Client) GetIdentityFlagsFromAPI(ctx context.Context, identifier string,
243254 Transient * bool `json:"transient,omitempty"`
244255 }{Identifier : identifier , Traits : traits }
245256 req := c .client .NewRequest ()
246- maybeEc := ctx .Value (contextKeyEvaluationContext )
247- if maybeEc != nil {
248- ec := maybeEc .(* EvaluationContext )
257+ ec , ok := GetEvaluationContextFromCtx (ctx )
258+ if ok {
249259 envCtx := ec .Environment
250260 if envCtx != nil {
251261 req .SetHeader (EnvironmentKeyHeader , envCtx .APIKey )
0 commit comments