### Basic OpenFeature Go SDK Usage Source: https://github.com/open-feature/go-sdk/blob/main/README.md This example demonstrates how to register a NoopProvider, create a default client, and evaluate a boolean feature flag. Ensure you have Go 1.25 or later installed. ```go package main import ( "fmt" "context" "github.com/open-feature/go-sdk/openfeature" ) func main() { // Register your feature flag provider openfeature.SetProviderAndWait(openfeature.NoopProvider{}) // Create a new client client := openfeature.NewDefaultClient() // Evaluate your feature flag v2Enabled := client.Boolean( context.TODO(), "v2_enabled", true, openfeature.EvaluationContext{}, ) // Use the returned flag value if v2Enabled { fmt.Println("v2 is enabled") } } ``` -------------------------------- ### Production OpenFeature Go SDK Setup with Context and Hooks Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/configuration.md A comprehensive setup for production environments. It includes context-aware provider setup, global evaluation context, a logging hook, and client evaluation with specific context. Ensure to call Shutdown() in a defer statement. ```go package main import ( "context" "log/slog" "os" "time" "github.com/open-feature/go-sdk/openfeature" "github.com/open-feature/go-sdk/openfeature/hooks" "github.com/open-feature/go-sdk/openfeature/memprovider" ) func main() { // Setup logging logger := slog.New(slog.NewJSONHandler(os.Stderr, nil)) // Setup provider with context ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() provider := memprovider.NewInMemoryProvider(map[string]memprovider.InMemoryFlag{ "feature": { Key: "feature", State: memprovider.Enabled, DefaultVariant: "off", Variants: map[string]any{"on": true, "off": false}, }, }) err := openfeature.SetProviderWithContextAndWait(ctx, provider) if err != nil { log.Fatalf("Provider setup failed: %v", err) } // Setup global context openfeature.SetEvaluationContext(openfeature.NewTargetlessEvaluationContext( map[string]any{ "environment": "production", "version": "1.0.0", }, )) // Setup logging hook loggingHook := hooks.NewLoggingHook(false, logger) openfeature.AddHooks(loggingHook) // Create client client := openfeature.NewDefaultClient() // Evaluate flag with context evalCtx := openfeature.NewEvaluationContext("user-123", map[string]any{ "email": "user@example.com", }) value := client.Boolean(context.Background(), "feature", false, evalCtx) // Cleanup defer openfeature.Shutdown() } ``` -------------------------------- ### Track Purchase Event Example Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Example demonstrating how to track a 'purchase' event with associated details like currency and product ID. Requires creating TrackingEventDetails and an EvaluationContext. ```go details := openfeature.NewTrackingEventDetails(99.99) details = details.Add("currency", "USD").Add("product_id", "product-123") client.Track( context.Background(), "purchase", openfeature.NewEvaluationContext("user-123", map[string]any{}), details, ) ``` -------------------------------- ### Go Code Block Example Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/README.md Illustrates the standard format for Go code examples within the documentation. ```go // Go code examples func MyFunction() { } ``` -------------------------------- ### Minimal OpenFeature Go SDK Setup Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/configuration.md This is the most basic setup for the OpenFeature Go SDK. It registers a NoopProvider and creates a default client. Use this for simple applications or testing. ```go package main import ( "context" "github.com/open-feature/go-sdk/openfeature" ) func main() { openfeature.SetProviderAndWait(openfeature.NoopProvider{}) client := openfeature.NewDefaultClient() value := client.Boolean(context.Background(), "feature", false, openfeature.EvaluationContext{}) // Use value } ``` -------------------------------- ### ClientMetadata Usage Example Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/types.md Demonstrates how to create a client and access its metadata. Ensure the client is initialized with a domain string. ```go client := openfeature.NewClient("my-domain") metadata := client.Metadata() fmt.Println(metadata.Domain()) // "my-domain" ``` -------------------------------- ### Named Provider Setup in Go Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/configuration.md Configure providers for specific domains using SetNamedProvider, with options for synchronous setup and context-aware initialization. Domain names should be lowercase alphanumeric with hyphens. ```go // Set provider for a specific domain err := openfeature.SetNamedProvider("analytics", analyticsProvider) ``` ```go // With wait err := openfeature.SetNamedProviderAndWait("analytics", analyticsProvider) ``` ```go // With context err := openfeature.SetNamedProviderWithContext(ctx, "analytics", analyticsProvider) ``` ```go // With context and wait err := openfeature.SetNamedProviderWithContextAndWait(ctx, "analytics", analyticsProvider) ``` -------------------------------- ### Install OpenFeature Go SDK Source: https://github.com/open-feature/go-sdk/blob/main/README.md Use this command to add the OpenFeature Go SDK to your project dependencies. ```shell go get github.com/open-feature/go-sdk ``` -------------------------------- ### EvaluationContext Usage Example Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/types.md Shows how to create an evaluation context with a targeting key and attributes for dynamic flag evaluation. ```go ctx := openfeature.NewEvaluationContext( "user-456", map[string]any{ "email": "user@example.com", "plan": "premium", "country": "US", }, ) value := client.Boolean(context.Background(), "flag", false, ctx) ``` -------------------------------- ### Example Usage of Evaluation Options Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/types.md Demonstrates how to use functional options like WithHooks and WithHookHints when evaluating a boolean flag. ```go value := client.Boolean( ctx, "flag", false, evalCtx, openfeature.WithHooks(hook1, hook2), openfeature.WithHookHints(hints), ) ``` -------------------------------- ### Context-Aware Provider Setup in Go Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/configuration.md Set up a feature flag provider with context for timeout and cancellation, supporting context-aware initialization. Use WithContextAndWait for critical startup paths. ```go // With context and async initialization ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) deferr cancel() err := openfeature.SetProviderWithContext(ctx, provider) ``` ```go // With context and wait for initialization err := openfeature.SetProviderWithContextAndWait(ctx, provider) ``` -------------------------------- ### Basic Provider Setup in Go Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/configuration.md Configure a feature flag provider asynchronously (default) or synchronously by waiting for initialization. Ensure the provider implements the FeatureProvider interface. ```go // Asynchronous setup (default) err := openfeature.SetProvider(provider) ``` ```go // Synchronous setup (wait for initialization) err := openfeature.SetProviderAndWait(provider) ``` -------------------------------- ### Instantiate and Use ProviderInitError in Go Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/errors.md Demonstrates how to create an instance of ProviderInitError and use its Error() method to get a string representation. ```go err := &openfeature.ProviderInitError{ ErrorCode: openfeature.GeneralCode, Message: "failed to connect to feature flag service", } fmt.Println(err.Error()) ``` -------------------------------- ### Multi-Domain OpenFeature Go SDK Setup Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/configuration.md Configure multiple providers for different domains within the same application. This allows for specialized feature flag management per domain, using named clients to access specific providers. ```go package main import ( "context" "github.com/open-feature/go-sdk/openfeature" "github.com/open-feature/go-sdk/openfeature/memprovider" ) func main() { // Default provider defaultProvider := memprovider.NewInMemoryProvider(map[string]memprovider.InMemoryFlag{}) openfeature.SetProviderAndWait(defaultProvider) // Domain-specific providers analyticsProvider := memprovider.NewInMemoryProvider(map[string]memprovider.InMemoryFlag{ "analytics_feature": { Key: "analytics_feature", State: memprovider.Enabled, DefaultVariant: "enabled", Variants: map[string]any{"enabled": true, "disabled": false}, }, }) openfeature.SetNamedProviderAndWait("analytics", analyticsProvider) // Create domain-scoped clients defaultClient := openfeature.NewDefaultClient() analyticsClient := openfeature.NewClient("analytics") // Evaluate flags defaultValue := defaultClient.Boolean(context.Background(), "flag", false, openfeature.EvaluationContext{}) analyticsValue := analyticsClient.Boolean(context.Background(), "analytics_feature", false, openfeature.EvaluationContext{}) } ``` -------------------------------- ### Implementing a Custom Strategy with Options Source: https://github.com/open-feature/go-sdk/blob/main/openfeature/multi/README.md Example of building a custom strategy using the WithCustomStrategy option. The provided function acts as a factory to wrap the slice of NamedProvider instances within the StrategyFn. ```go option := multi.WithCustomStrategy(func(providers []NamedProvider) StrategyFn[FlagTypes] { return func[T FlagTypes](ctx context.Context, flag string, defaultValue T, flatCtx openfeature.FlattenedContext) openfeature.GenericResolutionDetail[T] { // implementation // ... } }) ``` -------------------------------- ### FlagMetadata Usage Example Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/types.md Demonstrates retrieving string and float metadata from evaluation details. Ensure to handle potential errors when accessing metadata fields. ```go details, _ := client.BooleanValueDetails(ctx, "flag", false, evalCtx) metadata := details.FlagMetadata if owner, err := metadata.GetString("owner_email"); err == nil { fmt.Println("Flag owner:", owner) } if rollout, err := metadata.GetFloat("rollout_percentage"); err == nil { fmt.Printf("Rollout: %.1f%%\n", rollout) } ``` -------------------------------- ### ResolutionDetail Usage Example Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/types.md Shows how to access variant, reason, and error details from a resolution result. Check ErrorCode to determine if an error occurred. ```go details, _ := client.BooleanValueDetails(ctx, "flag", false, evalCtx) fmt.Println("Variant:", details.Variant) fmt.Println("Reason:", details.Reason) if details.ErrorCode != "" { fmt.Println("Error:", details.ErrorMessage) } ``` -------------------------------- ### Get ClientMetadata Domain Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Retrieves the domain associated with the client metadata. ```go func (cm ClientMetadata) Domain() string ``` -------------------------------- ### Implement StateHandler Interface Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/index.md Optional interface for providers that require initialization and shutdown logic. The Init method is called once during provider setup, and Shutdown is called when the provider is no longer needed. ```go type StateHandler interface { Init(evaluationContext EvaluationContext) error Shutdown() } ``` -------------------------------- ### GenericEvaluationDetails Usage Example Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/types.md Demonstrates retrieving boolean evaluation details, including the resolved value, reason, and variant. Check for errors before accessing details. ```go details, err := client.BooleanValueDetails(ctx, "flag", false, evalCtx) if err == nil { fmt.Printf("Value: %v, Reason: %s, Variant: %s\n", details.Value, details.Reason, details.Variant) } ``` -------------------------------- ### Create TrackingEventDetails Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Creates a new TrackingEventDetails instance with a specified numeric value. Use this to initialize event details, for example, with a purchase amount. ```go func NewTrackingEventDetails(value float64) TrackingEventDetails ``` -------------------------------- ### InMemoryProvider with Context Evaluator Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/configuration.md Configures the InMemoryProvider with a custom ContextEvaluator for dynamic flag targeting based on context. This example targets a 'treatment' variant for a 'user-vip'. ```go flags := map[string]memprovider.InMemoryFlag{ "user_targeting": { Key: "user_targeting", State: memprovider.Enabled, DefaultVariant: "control", Variants: map[string]any{ "control": false, "treatment": true, }, ContextEvaluator: &func(flag memprovider.InMemoryFlag, flatCtx openfeature.FlattenedContext) (any, openfeature.ProviderResolutionDetail) { // Custom evaluation logic if userId, ok := flatCtx["user_id"]; ok && userId == "user-vip" { return true, openfeature.ProviderResolutionDetail{ Reason: openfeature.TargetingMatchReason, Variant: "treatment", } } return false, openfeature.ProviderResolutionDetail{ Reason: openfeature.DefaultReason, Variant: "control", } }, }, } ``` -------------------------------- ### Set Default OpenFeature Provider with Context and Wait Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Sets the default FeatureProvider with context-aware initialization and waits for completion. This is useful for managing provider setup with timeouts or cancellation signals. ```go ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() er := openfeature.SetProviderWithContextAndWait(ctx, myProvider) if err != nil { log.Fatalf("Provider setup failed: %v", err) } ``` -------------------------------- ### Set and Get Transaction Context in Go Source: https://github.com/open-feature/go-sdk/blob/main/README.md Demonstrates how to set, retrieve, and merge transaction-specific evaluation context within a Go application using the Open Feature SDK. This context is automatically applied to flag evaluations. ```go import "github.com/open-feature/go-sdk/openfeature" // set the TransactionContext ctx := openfeature.WithTransactionContext(context.TODO(), openfeature.EvaluationContext{}) // get the TransactionContext from a context ec := openfeature.TransactionContext(ctx) // merge an EvaluationContext with the existing TransactionContext, preferring // the context that is passed to MergeTransactionContext tCtx := openfeature.MergeTransactionContext(ctx, openfeature.EvaluationContext{}) // use TransactionContext in a flag evaluation _ = client.Boolean(tCtx, .... ``` -------------------------------- ### Initialize Provider and Create Client Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/index.md Demonstrates the basic steps to initialize an OpenFeature provider and create a client for flag evaluation. ```go SetProvider(provider) SetProviderAndWait(provider) SetEvaluationContext(...) AddHooks(hook1, hook2) client := NewDefaultClient() client.SetEvaluationContext(...) value := client.Boolean(ctx, "flag-key", defaultValue, evalCtx) Shutdown() ShutdownWithContext(ctx) ``` -------------------------------- ### Initialize Multi-Provider with First Match Strategy Source: https://github.com/open-feature/go-sdk/blob/main/openfeature/multi/README.md Demonstrates how to create a new Multi-Provider using the `First Match` strategy and register it with OpenFeature. Ensure all necessary providers are imported and configured. ```go import ( "github.com/open-feature/go-sdk/openfeature" "github.com/open-feature/go-sdk/openfeature/multi" "github.com/open-feature/go-sdk/openfeature/memprovider" ) mprovider, err := multi.NewProvider( multi.StrategyFirstMatch, multi.WithProvider("providerA", memprovider.NewInMemoryProvider(/*...*/)), multi.WithProvider("providerB", myCustomProvider), ) if err != nil { return err } openfeature.SetNamedProviderAndWait("multiprovider", mprovider) ``` -------------------------------- ### Get ClientMetadata Name (Deprecated) Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md This method is deprecated and should not be used. Use Domain() instead to get the client's domain name. ```go func (cm ClientMetadata) Name() string ``` -------------------------------- ### Register Providers and Create Clients in Go Source: https://github.com/open-feature/go-sdk/blob/main/README.md Shows how to register both the default provider and named providers, and then create clients associated with them. ```go import ( "github.com/open-feature/go-sdk/openfeature" "github.com/open-feature/go-sdk/openfeature/memprovider" ) // Registering the default provider openfeature.SetProviderAndWait(openfeature.NoopProvider{}) // Registering a named provider openfeature.SetNamedProvider("clientForCache", memprovider.NewInMemoryProvider(map[string]memprovider.InMemoryFlag{})) // A Client backed by default provider clientWithDefault := openfeature.NewDefaultClient() // A Client backed by NewCachedProvider clientForCache := openfeature.NewClient("clientForCache") ``` -------------------------------- ### Get Numeric Value from TrackingEventDetails Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Retrieves the primary numeric value associated with the tracking event. ```go func (t TrackingEventDetails) Value() float64 ``` -------------------------------- ### Simple Flag Evaluation in Go Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/README.md Demonstrates a basic flag evaluation workflow. Ensure the provider is set before creating a client and remember to shut down the SDK when done. ```go openfeature.SetProviderAndWait(provider) client := openfeature.NewDefaultClient() value := client.Boolean(ctx, "flag", false, openfeature.EvaluationContext{}) defer openfeature.Shutdown() ``` -------------------------------- ### Commit with Signed-off-by Source: https://github.com/open-feature/go-sdk/blob/main/CONTRIBUTING.md Example of a commit message adhering to Conventional Commits and including the Signed-off-by line, required for contributions. ```git fix: solve all the problems Signed-off-by: John Doe ``` -------------------------------- ### Get Client Metadata from HookContext Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Use this method within a hook to retrieve metadata associated with the OpenFeature client. ```go func (h HookContext) ClientMetadata() ClientMetadata ``` -------------------------------- ### Get Flag Key from HookContext Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Use this method within a hook to retrieve the key of the flag currently being evaluated. ```go func (h HookContext) FlagKey() string ``` -------------------------------- ### Configure and Use Logging Hook in Go Source: https://github.com/open-feature/go-sdk/blob/main/README.md Demonstrates how to set up and use the LoggingHook with slog for detailed flag evaluation logging. Ensure your log level is set to debug to see the output. ```go package main import ( "context" "log/slog" "os" "github.com/open-feature/go-sdk/openfeature" "github.com/open-feature/go-sdk/openfeature/hooks" "github.com/open-feature/go-sdk/openfeature/memprovider" ) func main() { // Register an in-memory provider with no flags openfeature.SetNamedProviderAndWait("example", memprovider.NewInMemoryProvider(map[string]memprovider.InMemoryFlag{})) // Configure slog handler := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}) logger := slog.New(handler) // Register a logging hook globally to run on all evaluations loggingHook := hooks.NewLoggingHook(false, logger) openfeature.AddHooks(loggingHook) // Create a new client client := openfeature.NewClient("example") // Attempt to evaluate a flag that doesn't exist _ = client.Boolean(context.TODO(), "not-exist", true, openfeature.EvaluationContext{}) } ``` -------------------------------- ### Get Provider Metadata from HookContext Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Use this method within a hook to retrieve metadata associated with the flag evaluation provider. ```go func (h HookContext) ProviderMetadata() Metadata ``` -------------------------------- ### Get Default Value from HookContext Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Use this method within a hook to access the default value that was provided for the flag evaluation. ```go func (h HookContext) DefaultValue() any ``` -------------------------------- ### Add Global and Client Event Handlers in Go Source: https://github.com/open-feature/go-sdk/blob/main/README.md Illustrates how to attach event handlers for provider events, both globally and to specific clients. This allows reacting to state changes like provider readiness or errors. ```go import "github.com/open-feature/go-sdk/openfeature" ... // Assume context and other necessary imports are present var readyHandlerCallback = func(details openfeature.EventDetails) { // callback implementation } // Global event handler openfeature.AddHandler(openfeature.ProviderReady, &readyHandlerCallback) ... // Assume client initialization code is present var providerErrorCallback = func(details openfeature.EventDetails) { // callback implementation } client := openfeature.NewDefaultClient() // Client event handler client.AddHandler(openfeature.ProviderError, &providerErrorCallback) ``` -------------------------------- ### Get Specific Attribute from TrackingEventDetails Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Retrieves the value of a specific tracking attribute using its key. Returns any if the attribute is not found. ```go func (t TrackingEventDetails) Attribute(key string) any ``` -------------------------------- ### Construct ClientMetadata Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Use this function to create ClientMetadata for testing purposes. It requires a client domain string. ```go func NewClientMetadata(domain string) ClientMetadata ``` -------------------------------- ### Get Float from FlagMetadata Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Retrieves a float value from flag metadata using a specified key. Handles both float32 and float64 types. ```go func (f FlagMetadata) GetFloat(key string) (float64, error) ``` -------------------------------- ### Set Provider Initialization Timeouts Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/index.md Use `context.WithTimeout` when setting a provider to ensure the initialization process does not hang indefinitely. This is crucial for managing application startup time. ```go ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) deferr cancel() err := openfeature.SetProviderWithContextAndWait(ctx, provider) ``` -------------------------------- ### Get Evaluation Context from HookContext Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Use this method within a hook to access the complete evaluation context for the current flag evaluation. ```go func (h HookContext) EvaluationContext() EvaluationContext ``` -------------------------------- ### Get All Attributes from Evaluation Context Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Retrieve a copy of all attributes present in the EvaluationContext. Modifying the returned map will not affect the original context. ```go func (e EvaluationContext) Attributes() map[string]any ``` -------------------------------- ### Set NoopProvider Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/configuration.md Use the NoopProvider for development and testing. It bypasses readiness checks and always returns default values. ```go openfeature.SetProvider(openfeature.NoopProvider{}) client := openfeature.NewDefaultClient() ``` -------------------------------- ### Create Default OpenFeature Client Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Creates a new client instance connected to the default provider. Use this when you don't need to manage multiple named providers. ```go client := openfeature.NewDefaultClient() value := client.Boolean(context.Background(), "flag-key", false, openfeature.EvaluationContext{}) ``` -------------------------------- ### Check Flag Type in Go Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/types.md Example demonstrating how to check the type of a resolved flag value using the 'Boolean' constant from the 'Type' enum. ```go details, _ := client.BooleanValueDetails(ctx, "flag", false, evalCtx) if details.FlagType == openfeature.Boolean { fmt.Println("This is a boolean flag") } ``` -------------------------------- ### Handle Provider Not Ready State in Go Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/errors.md Provides a pattern to check if the Open Feature client is in a ReadyState before evaluating flags. If not ready, it logs a message and returns a default value. ```go client := openfeature.NewDefaultClient() // Short-circuit evaluation when provider isn't ready if client.State() != openfeature.ReadyState { log.Println("Provider not ready, using default value") return false } value := client.Boolean(ctx, "feature", false, evalCtx) ``` -------------------------------- ### Get All Attributes from TrackingEventDetails Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Returns a copy of all attributes stored within the tracking event details. This provides a snapshot of all added contextual information. ```go func (t TrackingEventDetails) Attributes() map[string]any ``` -------------------------------- ### Handle Provider Not Ready or Fatal States Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/index.md Implement checks for `NotReadyState` and `FatalState` to gracefully handle scenarios where the provider is still initializing or has encountered an unrecoverable error. This allows falling back to default values. ```go if client.State() == openfeature.NotReadyState { // Provider still initializing, use defaults return defaultValue } if client.State() == openfeature.FatalState { // Provider in unrecoverable state return defaultValue } ``` -------------------------------- ### Import Main OpenFeature Package Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/README.md Use this import statement to include the main OpenFeature Go SDK package in your project. ```go import "github.com/open-feature/go-sdk/openfeature" ``` -------------------------------- ### NewClient - OpenFeature Go SDK Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Creates a new Client bound to the provider registered for a specific domain. Use this to instantiate a client for a particular service or feature set. ```go func NewClient(domain string) *Client ``` ```go client := openfeature.NewClient("my-domain") ``` -------------------------------- ### Provider Not Ready Handling Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/errors.md Illustrates how to check the client's state before evaluation to avoid issues when the provider is not yet ready, ensuring default values are used in such cases. ```APIDOC ## Provider Not Ready Handling ```go client := openfeature.NewDefaultClient() // Short-circuit evaluation when provider isn't ready if client.State() != openfeature.ReadyState { log.Println("Provider not ready, using default value") return false } value := client.Boolean(ctx, "feature", false, evalCtx) ``` ``` -------------------------------- ### Get Boolean from FlagMetadata Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Retrieves a boolean value from flag metadata using a specified key. Returns an error if the key does not exist or the value is not a boolean. ```go func (f FlagMetadata) GetBool(key string) (bool, error) ``` -------------------------------- ### Get String from FlagMetadata Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Retrieves a string value from flag metadata using a specified key. Returns an error if the key does not exist or the value is not a string. ```go func (f FlagMetadata) GetString(key string) (string, error) ``` ```go details, _ := client.BooleanValueDetails(ctx, "flag", false, evalCtx) if description, err := details.FlagMetadata.GetString("description"); err == nil { fmt.Println(description) } ``` -------------------------------- ### Get Flag Type from HookContext Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Use this method within a hook to determine the data type of the flag being evaluated (e.g., Boolean, String, Int). ```go func (h HookContext) FlagType() Type ``` -------------------------------- ### Set Flags for Test Suite with TestProvider Source: https://github.com/open-feature/go-sdk/blob/main/README.md Use `testing.NewTestProvider` to create a test provider and `testProvider.UsingFlags` to set flags for a test suite. Remember to clean up flags using `testProvider.Cleanup()` after each test. ```go import ( "github.com/open-feature/go-sdk/openfeature" "github.com/open-feature/go-sdk/openfeature/testing" ) testProvider := testing.NewTestProvider() er := openfeature.SetProviderAndWait(testProvider) if err != nil { t.Errorf("unable to set provider") } // configure flags for this test suite tests := map[string]struct { flags map[string]memprovider.InMemoryFlag want bool }{ "test when flag is true": { flags: map[string]memprovider.InMemoryFlag{ "my_flag": { State: memprovider.Enabled, DefaultVariant: "on", Variants: map[string]any{ "on": true, }, }, }, want: true, }, "test when flag is false": { flags: map[string]memprovider.InMemoryFlag{ "my_flag": { State: memprovider.Enabled, DefaultVariant: "off", Variants: map[string]any{ "off": false, }, }, }, want: false, }, } for name, tt := range tests { tt := tt name := name t.Run(name, func(t *testing.T) { // be sure to clean up your flags defer testProvider.Cleanup() testProvider.UsingFlags(t, tt.flags) // your code under test got := functionUnderTest() if got != tt.want { t.Fatalf("uh oh, value is not as expected: got %v, want %v", got, tt.want) } }) } ``` -------------------------------- ### Implement OpenFeature Go SDK Provider Source: https://github.com/open-feature/go-sdk/blob/main/README.md Implement the FeatureProvider interface to create a custom provider. This includes methods for metadata, hooks, and flag evaluations for various data types. Optional Init and Shutdown methods can be implemented for lifecycle management. ```go package myfeatureprovider import ( "context" "github.com/open-feature/go-sdk/openfeature" ) // MyFeatureProvider implements the FeatureProvider interface and provides functions for evaluating flags type MyFeatureProvider struct{} // Required: Methods below implements openfeature.FeatureProvider interface // This is the core interface implementation required from a provider // Metadata returns the metadata of the provider func (i MyFeatureProvider) Metadata() openfeature.Metadata { return openfeature.Metadata{ Name: "MyFeatureProvider", } } // Hooks returns a collection of openfeature.Hook defined by this provider func (i MyFeatureProvider) Hooks() []openfeature.Hook { // Hooks that should be included with the provider return []openfeature.Hook{} } // BooleanEvaluation returns a boolean flag func (i MyFeatureProvider) BooleanEvaluation(ctx context.Context, flag string, defaultValue bool, flatCtx openfeature.FlattenedContext) openfeature.BoolResolutionDetail { // code to evaluate boolean } // StringEvaluation returns a string flag func (i MyFeatureProvider) StringEvaluation(ctx context.Context, flag string, defaultValue string, flatCtx openfeature.FlattenedContext) openfeature.StringResolutionDetail { // code to evaluate string } // FloatEvaluation returns a float flag func (i MyFeatureProvider) FloatEvaluation(ctx context.Context, flag string, defaultValue float64, flatCtx openfeature.FlattenedContext) openfeature.FloatResolutionDetail { // code to evaluate float } // IntEvaluation returns an int flag func (i MyFeatureProvider) IntEvaluation(ctx context.Context, flag string, defaultValue int64, flatCtx openfeature.FlattenedContext) openfeature.IntResolutionDetail { // code to evaluate int } // ObjectEvaluation returns an object flag func (i MyFeatureProvider) ObjectEvaluation(ctx context.Context, flag string, defaultValue any, flatCtx openfeature.FlattenedContext) openfeature.InterfaceResolutionDetail { // code to evaluate object } // Optional: openfeature.StateHandler implementation // Providers can opt-in for initialization & shutdown behavior by implementing this interface // Init holds initialization logic of the provider func (i MyFeatureProvider) Init(evaluationContext openfeature.EvaluationContext) error { // code to initialize your provider } // Shutdown define the shutdown operation of the provider func (i MyFeatureProvider) Shutdown() { // code to shutdown your provider } // Optional: openfeature.EventHandler implementation. // Providers can opt-in for eventing support by implementing this interface // EventChannel returns the event channel of this provider func (i MyFeatureProvider) EventChannel() <-chan openfeature.Event { // expose event channel from this provider. SDK listen to this channel and invoke event handlers } ``` -------------------------------- ### Get Specific Attribute from Evaluation Context Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Access a single attribute value from the EvaluationContext using its key. Returns any if the attribute exists, otherwise it will be nil. ```go func (e EvaluationContext) Attribute(key string) any ``` -------------------------------- ### Get Targeting Key from Evaluation Context Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Retrieve the targeting key associated with an EvaluationContext. This key uniquely identifies the subject for feature flag evaluations. ```go func (e EvaluationContext) TargetingKey() string ``` -------------------------------- ### Client.State - OpenFeature Go SDK Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Returns the current state of the associated provider. Check this state before evaluating flags to ensure readiness. ```go func (c *Client) State() State ``` ```go if client.State() == openfeature.ReadyState { // Safe to evaluate flags } ``` -------------------------------- ### Get Named Provider Metadata (Go) Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Retrieves metadata for a provider associated with a given domain name. This function is useful for inspecting provider information. ```go func NamedProviderMetadata(name string) Metadata ``` -------------------------------- ### Set Named Provider and Wait for Initialization (Go) Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Use this function to set a feature provider for a specific domain and ensure it has completed its initialization before proceeding. It returns an error if the provider fails to initialize. ```go func SetNamedProviderAndWait(domain string, provider FeatureProvider) error ``` -------------------------------- ### Client.Metadata - OpenFeature Go SDK Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Returns the client's metadata, including its associated domain. Useful for identifying the client or its configuration. ```go func (c *Client) Metadata() ClientMetadata ``` ```go metadata := client.Metadata() fmt.Println(metadata.Domain()) ``` -------------------------------- ### Get Default OpenFeature Provider Metadata Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Retrieves the metadata of the default FeatureProvider, which typically includes its name. This is useful for debugging or identifying the active provider. ```go metadata := openfeature.ProviderMetadata() fmt.Println(metadata.Name) ``` -------------------------------- ### Set Named Provider with Context (Go) Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Sets a feature provider for a domain using context for initialization, which is performed asynchronously. Initialization errors or context cancellation will be returned immediately. ```go func SetNamedProviderWithContext(ctx context.Context, domain string, provider FeatureProvider) error ``` -------------------------------- ### UnimplementedHook Struct and Usage Example Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/types.md An embeddable struct providing no-operation implementations for all Hook methods. Use this as a base for custom hooks to avoid implementing unused methods. ```go type UnimplementedHook struct{} ``` ```go type MyHook struct { openfeature.UnimplementedHook } func (h MyHook) After(ctx context.Context, hc openfeature.HookContext, details openfeature.InterfaceEvaluationDetails, hh openfeature.HookHints) error { // Custom logic return nil } ``` -------------------------------- ### Create OpenFeature EvaluationContext in Go Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/configuration.md Demonstrates creating EvaluationContext objects with and without a targeting key, and an empty context. Supports various attribute value types including strings, booleans, numbers, arrays, and nested objects. ```go // With targeting key and attributes ctx := openfeature.NewEvaluationContext("user-456", map[string]any{ "email": "user@example.com", "roles": []string{"admin", "user"}, "plan": "premium", "signup_date": "2023-01-15", }) // Without targeting key ctx := openfeature.NewTargetlessEvaluationContext(map[string]any{ "environment": "prod", "region": "us-east-1", }) // Empty context ctx := openfeature.EvaluationContext{} ``` -------------------------------- ### Register Named Providers for Multi-Tenancy Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/index.md Utilize `SetNamedProvider` to register multiple providers, each associated with a unique name. This enables the creation of separate clients for different tenants or environments. ```go openfeature.SetNamedProvider("tenant-1", provider1) openfeature.SetNamedProvider("tenant-2", provider2) tenant1Client := openfeature.NewClient("tenant-1") tenant2Client := openfeature.NewClient("tenant-2") ``` -------------------------------- ### Import OpenFeature In-Memory Provider Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/README.md Import the in-memory provider for OpenFeature Go SDK when you need a local, in-memory implementation of the provider interface. ```go import "github.com/open-feature/go-sdk/openfeature/memprovider" ``` -------------------------------- ### Track Events in Go Source: https://github.com/open-feature/go-sdk/blob/main/README.md Illustrates how to use the tracking API to associate user actions with feature flag evaluations, useful for experimentation. Note that provider support for tracking may vary. ```go // initialize a client client := openfeature.NewDefaultClient() // trigger tracking event action client.Track( context.TODO(), "visited-promo-page", openfeature.EvaluationContext{}, openfeature.NewTrackingEventDetails(99.77).Add("currencyCode", "USD"), ) ``` -------------------------------- ### NewClientMetadata Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Constructs ClientMetadata for testing purposes. It takes a domain string as input and returns a ClientMetadata object. ```APIDOC ## NewClientMetadata ### Description Constructs ClientMetadata for testing purposes. ### Signature ```go func NewClientMetadata(domain string) ClientMetadata ``` ### Parameters #### Path Parameters - **domain** (string) - Required - Client domain ### Returns - `ClientMetadata`: Client metadata ``` -------------------------------- ### Get Integer from FlagMetadata Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Retrieves an integer value from flag metadata using a specified key. Handles conversions from various integer types (int8, int16, int32, int64, int). ```go func (f FlagMetadata) GetInt(key string) (int64, error) ``` -------------------------------- ### Import OpenFeature Testing Utilities Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/README.md Use this import for accessing testing utilities within the OpenFeature Go SDK, useful for unit and integration testing of your feature flag implementations. ```go import "github.com/open-feature/go-sdk/openfeature/testing" ``` -------------------------------- ### Set Named Provider with Context and Wait (Go) Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md This function sets a feature provider for a domain, allowing for context-aware initialization with support for timeouts and cancellations. It waits for the initialization to complete and returns any errors encountered. ```go func SetNamedProviderWithContextAndWait(ctx context.Context, domain string, provider FeatureProvider) error ``` -------------------------------- ### Create In-Memory Provider Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Creates an in-memory feature flag provider for testing. Provide a map of flag definitions including their state, default variant, and available variants. ```go provider := memprovider.NewInMemoryProvider(map[string]memprovider.InMemoryFlag{ "my_flag": { State: memprovider.Enabled, DefaultVariant: "on", Variants: map[string]any{ "on": true, "off": false, }, }, }) openfeature.SetProviderAndWait(provider) ``` -------------------------------- ### SetProviderWithContextAndWait Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Sets the default FeatureProvider with context-aware initialization and waits for completion. If the provider implements ContextAwareStateHandler, InitWithContext will be called with the provided context. ```APIDOC ## SetProviderWithContextAndWait ### Description Sets the default FeatureProvider with context-aware initialization and waits for completion. If the provider implements ContextAwareStateHandler, InitWithContext will be called with the provided context. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method - `SetProviderWithContextAndWait(ctx context.Context, provider FeatureProvider) error` ### Parameters - **ctx** (context.Context) - Required - Context for initialization with timeout/cancellation support - **provider** (FeatureProvider) - Required - The provider to set as default ### Returns - `error`: Error if initialization fails or context is cancelled ### Example ```go ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() err := openfeature.SetProviderWithContextAndWait(ctx, myProvider) if err != nil { log.Fatalf("Provider setup failed: %v", err) } ``` ``` -------------------------------- ### Register Hooks in Go Source: https://github.com/open-feature/go-sdk/blob/main/README.md Shows how to add custom logic to the flag evaluation lifecycle using hooks. Hooks can be registered globally, on a specific client, or for a single evaluation. ```go // add a hook globally, to run on all evaluations openfeature.AddHooks(ExampleGlobalHook{}) // add a hook on this client, to run on all evaluations made by this client client := openfeature.NewDefaultClient() client.AddHooks(ExampleClientHook{}) // add a hook for this evaluation only value := client.Boolean( context.TODO(), "boolFlag", false, openfeature.EvaluationContext{}, openfeature.WithHooks(ExampleInvocationHook{}), ) ``` -------------------------------- ### Set Targeting Context in Go Source: https://github.com/open-feature/go-sdk/blob/main/README.md Demonstrates how to set evaluation context for targeting feature flags. Context can be set globally, per-client, or per-invocation. ```go // set a value to the global context openfeature.SetEvaluationContext(openfeature.NewTargetlessEvaluationContext( map[string]any{ "region": "us-east-1-iah-1a", }, )) // set a value to the client context client := openfeature.NewDefaultClient() client.SetEvaluationContext(openfeature.NewTargetlessEvaluationContext( map[string]any{ "version": "1.4.6", }, )) // set a value to the invocation context evalCtx := openfeature.NewEvaluationContext( "user-123", map[string]any{ "company": "Initech", }, ) boolValue := client.Boolean(context.TODO(), "boolFlag", false, evalCtx) ``` -------------------------------- ### Register a Custom Provider in Go Source: https://github.com/open-feature/go-sdk/blob/main/README.md Register your custom feature flag provider with the OpenFeature SDK. Replace `MyProvider{}` with your actual provider implementation. ```go openfeature.SetProviderAndWait(MyProvider{}) ``` -------------------------------- ### Client.AddHandler - OpenFeature Go SDK Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Adds a client-level event handler for provider events. Use this to react to changes in provider state or other lifecycle events. ```go func (c *Client) AddHandler(eventType EventType, callback EventCallback) ``` -------------------------------- ### Create TargetingKeyMissingResolutionError Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/errors.md Instantiate this error when a provider requires a targeting key for evaluation, but none was provided in the evaluation context. This is common for user-based targeting logic. ```go err := openfeature.NewTargetingKeyMissingResolutionError("targeting key required for user-based targeting") ``` -------------------------------- ### Pass Hook Hints for Evaluation (Go) Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Utilize `WithHookHints` to generate an evaluation option for passing specific hints to hooks during a single flag evaluation. Hints can provide contextual information to hooks. ```go func WithHookHints(hookHints HookHints) Option ``` -------------------------------- ### NewClient Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Creates a new Client bound to the provider registered for the given domain. ```APIDOC ## NewClient ### Description Creates a new Client bound to the provider registered for the given domain. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```go func NewClient(domain string) *Client ``` ### Parameters - **domain** (string) - Required - Domain name for provider binding ### Returns - `*Client`: New client instance ### Example ```go client := openfeature.NewClient("my-domain") ``` ``` -------------------------------- ### Configure InMemoryProvider with Flags Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/configuration.md Defines flags with keys, states, default variants, and variant values for the InMemoryProvider. Sets the provider for the OpenFeature SDK. ```go flags := map[string]memprovider.InMemoryFlag{ "feature_flag_1": { Key: "feature_flag_1", State: memprovider.Enabled, DefaultVariant: "on", Variants: map[string]any{ "on": true, "off": false, }, }, "feature_flag_2": { Key: "feature_flag_2", State: memprovider.Disabled, DefaultVariant: "off", Variants: map[string]any{ "on": true, "off": false, }, }, } provider := memprovider.NewInMemoryProvider(flags) er := openfeature.SetProviderAndWait(provider) ``` -------------------------------- ### SetNamedProviderWithContext Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Sets a FeatureProvider for a domain using a provided context. Initialization is asynchronous, allowing for cancellation or timeouts via the context. ```APIDOC ## SetNamedProviderWithContext ### Description Sets a FeatureProvider for a domain with context-aware initialization. Initialization is asynchronous. ### Function Signature ```go func SetNamedProviderWithContext(ctx context.Context, domain string, provider FeatureProvider) error ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for initialization with timeout/cancellation support - **domain** (string) - Required - Logical identifier for the domain - **provider** (FeatureProvider) - Required - The provider for this domain ### Returns - `error`: Immediately if provider is nil, or if context is cancelled ``` -------------------------------- ### Check Specific Error Codes in Go Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/errors.md Illustrates how to check the specific error code returned by a flag evaluation, such as FlagNotFoundCode, to handle different error scenarios. ```go details, err := client.BooleanValueDetails(ctx, "feature", false, evalCtx) if err != nil { fmt.Printf("Error Code: %s\n", details.ErrorCode) fmt.Printf("Error Message: %s\n", details.ErrorMessage) } // Check specific error code if details.ErrorCode == openfeature.FlagNotFoundCode { // Handle missing flag } ``` -------------------------------- ### SetNamedProviderWithContextAndWait Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Sets a FeatureProvider for a domain with context-aware initialization and explicitly waits for the initialization process to complete. This ensures the provider is ready before subsequent operations. ```APIDOC ## SetNamedProviderWithContextAndWait ### Description Sets a FeatureProvider for a domain with context-aware initialization and waits for completion. ### Function Signature ```go func SetNamedProviderWithContextAndWait(ctx context.Context, domain string, provider FeatureProvider) error ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for initialization with timeout/cancellation support - **domain** (string) - Required - Logical identifier for the domain - **provider** (FeatureProvider) - Required - The provider for this domain ### Returns - `error`: Error if initialization fails or context is cancelled ``` -------------------------------- ### Construct EvaluationContext with Targeting Key and Attributes Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Use this function to create an EvaluationContext with a specific targeting key and associated attributes. This is useful for identifying the subject of an evaluation. ```go ctx := openfeature.NewEvaluationContext( "user-123", map[string]any{ "email": "user@example.com", "plan": "premium", }, ) ``` -------------------------------- ### Construct Hook Context (Go) Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Use `NewHookContext` to create a `HookContext` object. This is primarily for testing custom hook implementations or providing a standardized context. ```go func NewHookContext( flagKey string, flagType Type, defaultValue any, clientMetadata ClientMetadata, providerMetadata Metadata, evaluationContext EvaluationContext, ) HookContext ``` -------------------------------- ### Optional Interfaces Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/index.md Optional interfaces that providers can implement to extend functionality, such as state management, context-aware initialization/shutdown, and event tracking. ```APIDOC ### Optional Interfaces **StateHandler** - For initialization and shutdown ```go type StateHandler interface { Init(evaluationContext EvaluationContext) error Shutdown() } ``` **ContextAwareStateHandler** - For context-aware init/shutdown (preferred) ```go type ContextAwareStateHandler interface { StateHandler InitWithContext(ctx context.Context, evaluationContext EvaluationContext) error ShutdownWithContext(ctx context.Context) error } ``` **Tracker** - For event tracking ```go type Tracker interface { Track(ctx context.Context, trackingEventName string, evaluationContext EvaluationContext, details TrackingEventDetails) } ``` **EventHandler** - For emitting events ```go type EventHandler interface { EventChannel() <-chan Event } ``` ``` -------------------------------- ### Construct Hook Hints from Map (Go) Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Create a `HookHints` object using `NewHookHints` by providing a map of string keys to any type of values. This is useful for passing structured hint data to hooks. ```go func NewHookHints(mapOfHints map[string]any) HookHints ``` -------------------------------- ### Create GeneralResolutionError Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/errors.md Use this constructor for any error reason not covered by specific error codes. It can optionally wrap an original error for more detailed debugging. ```go err := openfeature.NewGeneralResolutionError("unexpected provider error") ``` ```go // With wrapped error providerErr := someFunc() err := openfeature.NewGeneralResolutionError("provider failed", providerErr) ``` -------------------------------- ### SetProviderWithContext Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Sets the default FeatureProvider with context-aware initialization. If the provider implements ContextAwareStateHandler, InitWithContext will be called with the provided context. Initialization is asynchronous. ```APIDOC ## SetProviderWithContext ### Description Sets the default FeatureProvider with context-aware initialization. If the provider implements ContextAwareStateHandler, InitWithContext will be called with the provided context. Initialization is asynchronous. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method - `SetProviderWithContext(ctx context.Context, provider FeatureProvider) error` ### Parameters - **ctx** (context.Context) - Required - Context for initialization with timeout/cancellation support - **provider** (FeatureProvider) - Required - The provider to set as default ### Returns - `error`: Immediately if provider is nil or context is cancelled during setup ### Example ```go ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() err := openfeature.SetProviderWithContext(ctx, myProvider) ``` ``` -------------------------------- ### Import OpenFeature Logging Hook Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/README.md Include this import statement to use the logging hook provided by the OpenFeature Go SDK for observing feature flag evaluations. ```go import "github.com/open-feature/go-sdk/openfeature/hooks" ``` -------------------------------- ### Add Event Handler (Go) Source: https://github.com/open-feature/go-sdk/blob/main/_autodocs/api-reference.md Registers an event handler for specific provider events at the API level. This allows you to react to events like provider readiness. ```go var handler openfeature.EventCallback = &func(details openfeature.EventDetails) { fmt.Println("Provider event:", details.ProviderName) } openfeature.AddHandler(openfeature.ProviderReady, handler) ```