Skip to main content

Go

Install the latest version​

Github | pkg

go get github.com/quonfig/sdk-go/v2

The module path ends in /v2; the package name is still quonfig. Moving from v1? See UPGRADE to v2 in the CHANGELOG.

Initialize Client​

Add quonfig "github.com/quonfig/sdk-go/v2" to your imports.

Then, initialize the client with your SDK key:

sdk, err := quonfig.NewClient(quonfig.WithSdkKey(sdkKey))

Typical Usage​

We recommend using the SDK client as a singleton in your application.

import quonfig "github.com/quonfig/sdk-go/v2"

var quonfigSdk *quonfig.Client

func init() {
// Note: WithSdkKey is not needed if QUONFIG_BACKEND_SDK_KEY env var is set
sdk, err := quonfig.NewClient()
if err != nil {
panic(err)
}
quonfigSdk = sdk
}

API URLs​

By default the SDK derives all of its hostnames from QUONFIG_DOMAIN (default quonfig.com): it fetches config from https://primary.quonfig.com, streams live updates from https://stream.primary.quonfig.com, and automatically fails over to https://secondary.quonfig.com (on separate infrastructure). Failover and hedging are on by default — see Reliability for the full model.

Override the list with WithAPIURLs. Pass both a primary and a secondary URL to keep automatic failover; a single URL disables it (the SDK logs a warning at init):

sdk, err := quonfig.NewClient(
quonfig.WithSdkKey(sdkKey),
quonfig.WithAPIURLs([]string{
"https://primary.quonfig.com",
"https://secondary.quonfig.com",
}),
)

If Quonfig is unreachable at startup​

NewClient blocks until the first config arrives (a healthy boot takes about 100-300ms). While delivery is unreachable it retries with backoff for up to WithInitTimeout (default 10s), logging at WARN. What happens next is set by WithOnInitFailure:

ValueAt the timeout
quonfig.InitFailureFail (default)NewClient returns (nil, *quonfig.InitError). No client exists, so your process exits and your orchestrator's restart is the retry. If every delivery leg rejects the SDK key (401, 403, 404 or 410), it returns at once.
quonfig.InitFailureWaitNewClient keeps blocking and retrying until a config arrives, logging a WARN every 30s.
quonfig.InitFailureContinueNewClient returns a client with no config and logs an ERROR. It keeps retrying in the background; until it heals, getters answer ok=false with an error matching quonfig.ErrNotFound, and evaluation details report PROVIDER_NOT_READY.

WithInitTimeout of zero or less runs exactly one attempt, then applies OnInitFailure; it does not mean "no deadline".

client, err := quonfig.NewClient(
quonfig.WithSdkKey(key),
quonfig.WithOnInitFailure(quonfig.InitFailureFail), // the default
quonfig.WithInitTimeout(10*time.Second),
)
if err != nil {
var ie *quonfig.InitError
if errors.As(err, &ie) {
log.Fatalf("quonfig: %s after %s: %v", ie.Reason, ie.Elapsed, err) // timeout | unavailable | unauthorized
}
log.Fatal(err)
}

errors.Is(err, quonfig.ErrInitializationTimeout) is true when the legs hung until the timeout. client.Ready() reports whether the client holds a config, and client.WaitForReady(ctx) blocks until it does. Under InitFailureContinue, wire your readiness probe to Ready(). Getters never block waiting for initialization.

The older names quonfig.ReturnError and quonfig.ReturnZeroValue are deprecated aliases of InitFailureFail and InitFailureContinue. They still work and log a one-time WARN.

For how to choose between the three, see If Quonfig Is Unreachable at Startup.

Feature Flags​

For boolean flags, you can use the FeatureIsOn function:

enabled, ok := sdk.FeatureIsOn("my.feature.name", quonfig.NewContextSet())

Flags that don't exist yet are considered off, so you can happily add FeatureIsOn checks to your code before the flag is created.

FeatureIsOn never fails. It returns (true, true) only for a flag whose value is the bool true. A missing key, a flag with no matching rule, a non-bool value (a stored string "true" included) or any resolution error returns (false, false) and logs one WARN per key.

Feature flags don't have to return just true or false.

You can get other data types using Get* functions:

value, ok, err := sdk.GetStringValue("my.string.feature.name", quonfig.NewContextSet())
value, ok, err := sdk.GetJSONValue("my.json.feature.name", quonfig.NewContextSet())

Context​

Feature flags become more powerful when we give the flag evaluation rules more information to work with. We do this by providing context of the current user (and/or team, request, etc.)

Global Context​

When initializing the client, you can set a global context that will be used for all evaluations.

globalContext := quonfig.NewContextSet().
WithNamedContextValues("host", map[string]interface{}{
"name": os.Getenv("HOSTNAME"),
"region": os.Getenv("REGION"),
"cpu": runtime.NumCPU(),
})


sdk, err := quonfig.NewClient(
quonfig.WithSdkKey(sdkKey),
quonfig.WithGlobalContext(globalContext),
)

Global context is the least specific context and will be overridden by more specific context passed in at the time of evaluation.

Bound Context​

To make the best use of Quonfig in a web setting, we recommend setting context per-request. Setting this context for the life-cycle of the request means the Quonfig logger can be aware of your user/etc. for feature flags and targeted log levels and you won't have to explicitly pass context into your .FeatureIsOn and .Get* calls.

requestContext := quonfig.NewContextSet().
WithNamedContextValues("user", map[string]interface{}{
"name": currentUser.GetName(),
"email": currentUser.GetEmail(),
})

boundSdk := sdk.WithContext(requestContext)
enabled, ok := boundSdk.FeatureIsOn("my.feature.name")

Just-in-time Context​

You can also pass context when evaluating individual flags or config values. Just-in-time context is passed to the unbound client's FeatureIsOn/Get* methods (the context-bound client returned by WithContext takes only a key):

enabled, ok := sdk.FeatureIsOn("my.feature.name", quonfig.NewContextSet().
WithNamedContextValues("team", map[string]interface{}{
"name": currentTeam.GetName(),
"email": currentTeam.GetEmail(),
}))

Dynamic Config​

Config values are available via the Get* functions:

value, ok, err := sdk.GetJSONValue("slack.bot.config", quonfig.NewContextSet())

value, ok, err := sdk.GetStringValue("some.string.config", quonfig.NewContextSet())

value, ok, err := sdk.GetFloatValue("some.float.config", quonfig.NewContextSet())

Typed getters​

Every Get*Value(key, ctx) returns (value, ok, err). When ok is true, value is the config's value. When ok is false there is no value, so apply your default; err says why:

Situationokerr matchesLogged
Value of the getter's typetruenilno
Missing key, or no rule matchedfalsequonfig.ErrNotFound, or nilno
Value of another type (e.g. GetBoolValue on a string config)falsequonfig.ErrTypeMismatchonce per key
Malformed stored or ENV_VAR value (an int "twelve", a duration "30s")falsequonfig.ErrUnableToCoerceonce per key
ENV_VAR not setfalsequonfig.ErrMissingEnvVaronce per key
Secret cannot be decryptedfalsequonfig.ErrUnableToDecryptonce per key

The getters are GetStringValue, GetBoolValue, GetIntValue (int64), GetFloatValue, GetStringSliceValue, GetDurationValue (time.Duration) and GetJSONValue. Strings are never coerced: a stored "false" is a string, so GetBoolValue reports a type mismatch instead of false. The only conversions are between numbers, and only when exact: GetFloatValue reads an int config (30 becomes 30.0), and GetIntValue reads a double config holding a whole number within +/-(2^53-1) (3.0 becomes 3; 3.9 is a type mismatch, never truncated).

A wrong decryption key or an unset ENV_VAR therefore degrades to your defaults with one WARN per key. If a broken config must stop your service, check err and fail on it.

EvaluateDetails(key, ctx) returns the value with its Reason, Variant and, on failure, an ErrorCode: quonfig.ErrorCodeFlagNotFound, ErrorCodeTypeMismatch, ErrorCodeParseError, ErrorCodeProviderNotReady or ErrorCodeGeneral. The rules are the same in every Quonfig SDK; see Typed Getters, Defaults, and Error Codes.

Default Values for Configs​

Here we ask for the value of a config named max-jobs-per-second, falling back to 10 when there is no value.

maxJobsPerSecond, ok, err := sdk.GetIntValue("max-jobs-per-second", quonfig.NewContextSet())
if !ok {
if err != nil && !errors.Is(err, quonfig.ErrNotFound) {
log.Printf("max-jobs-per-second: %v", err) // wrong type, malformed value, ...
}
maxJobsPerSecond = 10 // default
}

If max-jobs-per-second holds an int, ok is true and maxJobsPerSecond is its value. Otherwise ok is false and we fall back to 10.

Developer overrides (qfg override)​

The qfg override CLI flips a flag for your developer machine without affecting anyone else. It does this by writing a top-priority rule on the flag keyed on the property quonfig-user.email. The SDK injects that property automatically whenever the qfg login token file is present, so the rule is dead code in production by construction (a server that never ran qfg login has no quonfig-user.email on its eval context, and the rule cannot fire).

Injection is on by default — when ~/.quonfig/tokens.json (written by qfg login) exists, the SDK reads it on init and merges quonfig-user.email = <userEmail> into the global context. Customer-supplied quonfig-user keys (set via WithGlobalContext) win on collision. If the file is missing or unparseable the SDK is a no-op — init still succeeds.

To opt out (e.g. on a shared box where qfg login has run):

sdk, err := quonfig.NewClient(
quonfig.WithSdkKey(sdkKey),
quonfig.WithQuonfigUserContext(false), // opt out
)

Or set QUONFIG_DEV_CONTEXT=false in the environment. Precedence: the explicit option wins, then QUONFIG_DEV_CONTEXT, then the default (true).

Telemetry note: quonfig-user.email flows through telemetry like any other context attribute. It only appears in dev-machine telemetry because production never injects it.

Dynamic Log Levels​

Log levels in Quonfig are stored as a log_level config (e.g. log-level.my-app). The SDK consults that config on every log call, so changes made in Quonfig take effect immediately via SSE with no polling or restart.

Concept​

  • One log_level config per app, keyed like log-level.my-app. Value is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL.
  • Tell the client which config to consult with WithLoggerKey(...).
  • ShouldLogPath(loggerPath, desiredLevel, ctx) pushes loggerPath into the evaluation context as quonfig-sdk-logging.key (verbatim — no normalization) so a single config can drive per-logger rules.
  • The ShouldLog(configKey, desiredLevel, ctx) primitive is also available when you want to evaluate a specific config without the convenience layer.
  • Logger names flowing through quonfig-sdk-logging.key are auto-captured by example-context telemetry, so the dashboard can auto-suggest rule targets.

Basic usage​

import (
quonfig "github.com/quonfig/sdk-go/v2"
)

client, _ := quonfig.NewClient(
quonfig.WithSdkKey("your-key"),
quonfig.WithLoggerKey("log-level.my-app"),
)

if client.ShouldLogPath("com.example.auth", "DEBUG", nil) {
// …
}

Rules​

Set levels with the qfg CLI. Each --target adds a rule that matches every logger whose name starts with that prefix:

# Default to INFO for every logger in this app
qfg log-level log-level.my-app --value=INFO

# Bump one subsystem to DEBUG
qfg log-level log-level.my-app --target=com.example.auth --value=DEBUG

# Quiet a chatty library, in one environment only
qfg log-level log-level.my-app --target=github.com/somelib --value=ERROR --environment=production

For rules on other properties, such as turning on DEBUG for one developer by user.email, add the rule in the Quonfig app. Dynamic Log Levels walks through rule order and shows the stored JSON.

Because the evaluator sees your full context — global context set via WithGlobalContext, per-call context passed into ShouldLogPath, and quonfig-sdk-logging.key — you can combine logger rules with user, environment, or request context to crank verbosity up for one user, one staging deploy, or one bad request, without touching anyone else.

slog handler​

The SDK ships a slog.Handler that wraps any inner handler and gates each record through ShouldLogPath:

import (
"log/slog"
"os"
quonfig "github.com/quonfig/sdk-go/v2"
)

client, _ := quonfig.NewClient(
quonfig.WithSdkKey("your-key"),
quonfig.WithLoggerKey("log-level.my-app"),
)

inner := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})
handler := quonfig.NewQuonfigHandler(client, inner, "com.example.auth")
logger := slog.New(handler)

logger.Debug("debug line")
logger.Info("info line")

If you'd rather let slog drive the level decision itself, use QuonfigLeveler:

leveler := quonfig.NewQuonfigLeveler(client, "com.example.auth")
handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: leveler,
})
logger := slog.New(handler)

Attaching per-request context​

Both NewQuonfigHandler and NewQuonfigLeveler read any *ContextSet attached to the context.Context passed through slog, so per-request user/team context flows into rule evaluation:

cs := quonfig.NewContextSet()
cs.WithNamedContextValues("user", map[string]interface{}{
"email": "developer@example.com",
})
ctx := quonfig.ContextWithContextSet(context.Background(), cs)

logger.DebugContext(ctx, "debug line — evaluated with user context")

Reference​

NameExampleDescription
WithLoggerKey(key)quonfig.WithLoggerKey("log-level.my-app")Tells the client which log_level config ShouldLogPath and the slog adapter should consult. Required for either.
ShouldLogPath(loggerPath, desiredLevel, ctx)client.ShouldLogPath("com.example.auth", "DEBUG", nil)Convenience. Uses LoggerKey + injects quonfig-sdk-logging.key = loggerPath so rules can target individual loggers.
ShouldLog(configKey, desiredLevel, ctx)client.ShouldLog("log-level.my-app", "DEBUG", nil)Primitive. Evaluates the named config directly — no auto-injection. Use when building a custom adapter.
NewQuonfigHandler(client, inner, loggerPath)slog.New(quonfig.NewQuonfigHandler(client, inner, "com.example.auth"))slog.Handler that gates each record through ShouldLogPath.
NewQuonfigLeveler(client, loggerPath)slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: leveler})slog.Leveler backed by Quonfig. Use when you want slog's own enabled-check path to see the dynamic level.
ContextWithContextSet(ctx, cs)ctx := quonfig.ContextWithContextSet(ctx, cs)Attach a *ContextSet to a context.Context so the slog adapter picks it up on each record.

Telemetry​

By default, Quonfig uploads telemetry that enables a number of useful features. You can alter or disable this behavior using the following options:

NameDescriptionDefault
collectEvaluationSummariesSend counts of config/flag evaluation results back to Quonfig to view in web apptrue
contextTelemetryModeUpload either context "shapes" (the names and data types your app uses in Quonfig contexts) or periodically send full example contextsquonfig.ContextTelemetryPeriodicExample

If you want to change any of these options, you can pass options when initializing the Quonfig SDK:

sdk, err := quonfig.NewClient(
quonfig.WithSdkKey(sdkKey),
quonfig.WithCollectEvaluationSummaries(true),
quonfig.WithContextTelemetryMode(quonfig.ContextTelemetryPeriodicExample),
)

Available context telemetry modes:

  • quonfig.ContextTelemetryNone - Don't upload any context information
  • quonfig.ContextTelemetryShapes - Upload only context shapes (names and data types)
  • quonfig.ContextTelemetryPeriodicExample - Periodically send full example contexts (default)

To disable all telemetry at once:

sdk, err := quonfig.NewClient(
quonfig.WithAllTelemetryDisabled(),
)

Delivery options​

How the SDK delivers telemetry, and what it does when the endpoint is slow or down, is the same in every SDK and is explained once on the Telemetry page. The Go option names and defaults:

OptionDefault
WithTelemetrySyncInterval60 * time.Second
WithTelemetryTimeout15 * time.Second
WithTelemetryConnectTimeout5 * time.Second
WithTelemetryMaxRetainedBatches5
WithTelemetryMaxRetainedBytes2097152 (2MB)
WithTelemetryMaxRetainedAge5 * time.Minute
WithTelemetryMaxEvaluationSummaries10000
WithTelemetryMaxContextShapeFields10000
WithTelemetryMaxExampleContexts10000
WithTelemetryMaxExampleContextsSeen100000

The timeout rides the request context, so it holds even when you pass your own client with WithHTTPClient; in that case your client's transport decides the connect timeout. Telemetry logs through the *slog.Logger from WithLogger (default slog.Default()).

A failed POST keeps its batch and resends it later, and Close() returns within 5s even if the telemetry endpoint hangs. With the default periodic_example context telemetry, each distinct context is sent as an example at most once per hour. The SDK remembers up to WithTelemetryMaxExampleContextsSeen recently sent contexts; a new context seen while that limit is full is picked up on a later evaluation once older entries expire. Evaluations and targeting are not affected. Earlier behavior is in the CHANGELOG.

Offline and Testing Modes​

Local Data Directory (datadir)​

For offline development, testing, or air-gapped environments, you can load configuration from a local Quonfig workspace directory on disk instead of connecting to the Quonfig API. See Local Workspace (datadir) for how to pull one.

Point the SDK at the workspace directory with WithDataDir, and select which environment to evaluate with WithEnvironment:

sdk, err := quonfig.NewClient(
quonfig.WithDataDir("/path/to/quonfig-workspace"),
quonfig.WithEnvironment("production"), // or "staging", "development"
)

Important notes:

  • WithDataDir loads entirely from disk — the SDK does not contact the API or open an SSE stream, and telemetry is effectively idle.
  • WithEnvironment (or the QUONFIG_ENVIRONMENT env var, which it overrides) selects which environment's values are evaluated from the local data.
  • To pick up edits to the directory while running, opt into WithDataDirAutoReload(true).

Invalid or revoked SDK key​

If Quonfig rejects the SDK key while the client is running, sdk-go stops streaming, probes every 150-300 seconds until the key works again, and logs one ERROR naming the HTTP status and host (never the key). The full rule is on the Reliability page.

While the key is rejected, ConnectionState() returns quonfig.ConnStateDisconnected ("disconnected"), never ConnStateFallingBack. Evaluation keeps serving the last installed configuration, and the client recovers by itself on the first accepted probe.

Reference​

Options​

client, err := quonfig.NewClient(
quonfig.WithSdkKey(os.Getenv("QUONFIG_BACKEND_SDK_KEY")), // or omit — auto-loaded from QUONFIG_BACKEND_SDK_KEY
quonfig.WithGlobalContext(globalContext),
quonfig.WithCollectEvaluationSummaries(true),
quonfig.WithContextTelemetryMode(quonfig.ContextTelemetryPeriodicExample),
)

Option Definitions​

NameDescriptionDefault
WithSdkKeyYour Quonfig SDK key (not needed if QUONFIG_BACKEND_SDK_KEY env var is set)from env var
WithAPIURLsOrdered list of API base URLs. SSE URL is derived by prepending stream. to the hostname["https://primary.quonfig.com", "https://secondary.quonfig.com"]
WithDataDirLoad configuration from a local Quonfig workspace directory instead of the API/SSE (offline/testing)"" (API mode)
WithEnvironmentWhich environment to evaluate when loading from a local data dir (overrides QUONFIG_ENVIRONMENT)from env var
WithGlobalContextSet a static context to be used as the base layer in all configuration evaluationempty
WithCollectEvaluationSummariesSend counts of config/flag evaluation results back to Quonfig to view in web apptrue
WithContextTelemetryModeUpload either context "shapes" (the names and data types your app uses in Quonfig contexts) or periodically send full example contextsquonfig.ContextTelemetryPeriodicExample
WithAllTelemetryDisabledDisable all telemetry (evaluation summaries and context telemetry)n/a
WithOnInitFailureWhat NewClient does if no config loads within WithInitTimeout: quonfig.InitFailureFail, InitFailureWait or InitFailureContinue (see startup). ReturnError / ReturnZeroValue are deprecated aliasesInitFailureFail
WithInitTimeoutHow long NewClient retries the initial config fetch before WithOnInitFailure applies, as a time.Duration (e.g. 10*time.Second)10s
WithLoggerKeyThe log_level config key consulted by ShouldLogPath and the slog adapter. No default — set it to enable the loggerPath convenience.""
WithQuonfigUserContextInject quonfig-user.email from ~/.quonfig/tokens.json (written by qfg login) into the global context. Pairs with qfg override. Default on, gated on the token file's presence (inert in prod). Pass false or set QUONFIG_DEV_CONTEXT=false to opt out.on (token-gated)