zenmanage

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 15 Imported by: 0

README

Zenmanage Go SDK

Go Reference CI Codacy Badge

Add feature flags to your Go services in minutes. Control feature rollouts, run A/B tests, and manage configuration without redeploying.

Why Zenmanage?

  • Fast local evaluation with cached rules
  • Context-aware targeting by user, org, or any attributes
  • Deterministic percentage rollouts via CRC32B bucketing
  • Safe defaults and defensive error handling
  • Testable interfaces and high unit test coverage

Installation

go get github.com/zenmanage/zenmanage-go

Requirements:

  • Go 1.25+
  • Server token prefixed with srv_

Key Compatibility

  • Server runtime only: environment tokens prefixed with srv_.
  • Client keys (cli_) and mobile keys (mob_) are rejected by this SDK at configuration time via ConfigurationError — this is a server-side SDK, matching the PHP core SDK's key requirements. Use zenmanage-javascript (or another browser/mobile SDK) for client- or mobile-key runtimes.

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/zenmanage/zenmanage-go"
)

func main() {
    cfg, err := zenmanage.NewConfigBuilder().
        WithEnvironmentToken("srv_your_server_key_here").
        Build()
    if err != nil {
        log.Fatal(err)
    }

    client := zenmanage.New(cfg)

    // Simple one-liner — evaluate a flag for a user ID.
    enabled, err := client.IsEnabled(context.Background(), "new-dashboard", "user-123")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("enabled:", enabled)
}

Common Use Cases

Simple API (single-call evaluation)
// Boolean flag
enabled, err := client.IsEnabled(ctx, "beta-feature", "user-123")

// String flag
color, err := client.GetString(ctx, "button-color", "user-123", "blue")

// Numeric flag
limit, err := client.GetNumber(ctx, "rate-limit", "user-123", 100)

Pass an empty string for userID to evaluate without user context (e.g. kill-switch flags).

Advanced API — fluent FlagManager
flag, err := client.Flags().
    WithContext(ctx).
    Single(context.Background(), "new-dashboard", false)
if err != nil {
    log.Fatal(err)
}
fmt.Println("enabled:", flag.IsEnabled())
Context-Based Targeting
ctx := zenmanage.NewContext(
    "user",
    "user-123",
    "Taylor",
    []zenmanage.Attribute{
        zenmanage.NewAttribute("country", []string{"US"}),
        zenmanage.NewAttribute("plan", []string{"pro"}),
    },
)

flag, err := client.Flags().
    WithContext(ctx).
    Single(context.Background(), "beta-program", false)
Percentage Rollouts
ctx := zenmanage.SingleContext("user", "user-123", "")
flag, err := client.Flags().
    WithContext(ctx).
    Single(context.Background(), "new-checkout-flow", false)
Defaults Collection
defaults := zenmanage.DefaultsFromMap(map[string]any{
    "new-ui": true,
    "api-version": "v2",
})

flag, err := client.Flags().
    WithDefaults(defaults).
    Single(context.Background(), "new-ui")
Fetch All Flags
flags, err := client.Flags().All(context.Background())
if err != nil {
    log.Fatal(err)
}
for _, flag := range flags {
    fmt.Println(flag.Key(), flag.Value())
}

All evaluates every flag in the environment against the manager's current context in one call. Unlike Single, it does not report per-flag usage — usage reporting is a signal tied to a specific evaluation decision, not a bulk retrieval.

Manual Usage Reporting

Single reports usage automatically on every evaluation. Call ReportUsage directly only when you need to record usage outside of a Single/All evaluation path (for example, after evaluating a flag some other way):

err := client.Flags().ReportUsage(context.Background(), "new-dashboard", false)

Configuration

Build configuration with fluent helpers:

  • WithEnvironmentToken
  • WithCacheTTL
  • WithCacheBackend: memory, filesystem, null
  • WithCacheDirectory
  • WithUsageReporting
  • WithAPIEndpoint
  • WithLogger
  • WithCache
  • WithHTTPClient

Or load from environment with ConfigFromEnvironment using:

  • ZENMANAGE_ENVIRONMENT_TOKEN
  • ZENMANAGE_CACHE_TTL
  • ZENMANAGE_CACHE_BACKEND
  • ZENMANAGE_CACHE_DIR
  • ZENMANAGE_ENABLE_USAGE_REPORTING
  • ZENMANAGE_API_ENDPOINT

Examples

See examples/README.md for parity samples:

  • simple_flags.go
  • context_based_flags.go
  • percentage_rollouts.go
  • ab_testing.go
  • caching.go
  • defaults.go
  • middleware.go

Middleware

The middleware sub-package provides framework integrations so flag evaluation fits naturally into HTTP request handling.

net/http (standard library)
import "github.com/zenmanage/zenmanage-go/middleware"

mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    enabled, err := middleware.IsEnabled(r.Context(), "new-feature")
    ...
})
http.ListenAndServe(":8080", middleware.InjectFlags(zmClient, mux))

If the request contains an X-User-ID header, the middleware automatically wires up a user context so rollout and targeting rules apply per-request.

Gin
go get github.com/zenmanage/zenmanage-go/middleware/gin
import ginmw "github.com/zenmanage/zenmanage-go/middleware/gin"

r := gin.Default()
r.Use(ginmw.InjectFlags(zmClient))

r.GET("/feature", func(c *gin.Context) {
    enabled, err := ginmw.IsEnabled(c, "new-feature")
    ...
})
Echo
go get github.com/zenmanage/zenmanage-go/middleware/echo
import echomw "github.com/zenmanage/zenmanage-go/middleware/echo"

e := echo.New()
e.Use(echomw.InjectFlags(zmClient))

e.GET("/feature", func(c echo.Context) error {
    enabled, err := echomw.IsEnabled(c, "new-feature")
    ...
})

Error Handling

Every error this SDK returns satisfies the shared zenmanage.Error interface, in addition to the standard error interface, so you can distinguish SDK errors from other errors with errors.As:

import (
    "errors"

    "github.com/zenmanage/zenmanage-go"
)

flag, err := client.Flags().Single(ctx, "unknown-flag")
if err != nil {
    var evalErr *zenmanage.EvaluationError
    var fetchErr *zenmanage.FetchRulesError
    switch {
    case errors.As(err, &evalErr):
        log.Println("flag not found:", evalErr.Message)
    case errors.As(err, &fetchErr):
        log.Println("failed to fetch rules:", fetchErr.Message, fetchErr.StatusCode)
    default:
        var zmErr zenmanage.Error
        if errors.As(err, &zmErr) {
            log.Println("SDK error:", zmErr)
        }
    }
}

// Or pass an inline default to avoid the "not found" error entirely.
flag, err = client.Flags().Single(ctx, "unknown-flag", false)

The concrete error types are ConfigurationError (invalid SDK setup), EvaluationError (rule/flag evaluation failure), FetchRulesError (failure loading rules from the API, with an optional StatusCode), and InvalidRulesError (malformed rules payload).

Testing

go test ./... -coverprofile=coverage.out

Linting

CI runs golangci-lint against the root module and each middleware submodule (.golangci.yml). Each is a separate Go module, so run it in each directory:

golangci-lint run ./...
(cd middleware/gin && golangci-lint run ./...)
(cd middleware/echo && golangci-lint run ./...)

Contributing

See CONTRIBUTING.md.

License

MIT. See LICENSE.

Documentation

Overview

Package zenmanage is the Zenmanage feature-flag SDK for Go server applications. It evaluates flags locally against cached rules fetched from the Zenmanage API, supporting context-based targeting, percentage rollouts, and usage reporting.

See the Zenmanage type for the main entry point, and the middleware sub-package for framework integrations.

Index

Constants

View Source
const Version = "1.0.0"

Version is the SDK semantic version.

Variables

This section is empty.

Functions

func CRC32B

func CRC32B(input string) uint32

CRC32B returns CRC32 checksum compatible with PHP hash('crc32b', ...).

func IsInBucket

func IsInBucket(salt, contextIdentifier string, percentage int) bool

IsInBucket computes deterministic rollout inclusion for percentage rollouts.

Types

type APIClient

type APIClient struct {
	// contains filtered or unexported fields
}

APIClient handles network communication with Zenmanage APIs.

func NewAPIClient

func NewAPIClient(cfg Config) *APIClient

NewAPIClient creates an API client.

func (*APIClient) FetchRules

func (c *APIClient) FetchRules(ctx context.Context) (RulesResponse, error)

FetchRules fetches the full rules payload from API/CDN.

func (*APIClient) ReportUsage

func (c *APIClient) ReportUsage(ctx context.Context, key string, contextData *Context, defaultValue any) error

ReportUsage emits usage telemetry for a flag key. defaultValue, when non-nil, is the fallback value the caller used because the flag couldn't be resolved from rules; it's sent as the X-ZEN-DEFAULT-VALUE header so it can be persisted and shown on the flag detail page.

type Attribute

type Attribute struct {
	// contains filtered or unexported fields
}

Attribute is a high-level context attribute helper.

func NewAttribute

func NewAttribute(key string, values []string) Attribute

NewAttribute creates a context attribute.

func (*Attribute) AddValue

func (a *Attribute) AddValue(value string)

AddValue appends a value to the attribute.

func (Attribute) Key

func (a Attribute) Key() string

Key returns the attribute key.

func (Attribute) Values

func (a Attribute) Values() []string

Values returns a copy of attribute values.

type Cache

type Cache interface {
	Get(key string) (value string, found bool, err error)
	Set(key, value string, ttl time.Duration) error
	Delete(key string) error
	Clear() error
}

Cache is the cache backend contract.

type Config

type Config struct {
	EnvironmentToken     string
	CacheTTL             time.Duration
	CacheBackend         string
	CacheDirectory       string
	EnableUsageReporting bool
	APIEndpoint          string
	Logger               Logger
	CustomCache          Cache
	HTTPClient           *http.Client
	ClientAgent          string
	SDKVersion           string
}

Config stores SDK configuration.

type ConfigBuilder

type ConfigBuilder struct {
	// contains filtered or unexported fields
}

ConfigBuilder builds SDK Config instances.

func ConfigFromEnvironment

func ConfigFromEnvironment() *ConfigBuilder

ConfigFromEnvironment creates a builder populated from env vars.

func NewConfigBuilder

func NewConfigBuilder() *ConfigBuilder

NewConfigBuilder creates a builder with defaults.

func (*ConfigBuilder) Build

func (b *ConfigBuilder) Build() (Config, error)

Build validates and returns config.

func (*ConfigBuilder) WithAPIEndpoint

func (b *ConfigBuilder) WithAPIEndpoint(endpoint string) *ConfigBuilder

WithAPIEndpoint sets custom API endpoint.

func (*ConfigBuilder) WithCache

func (b *ConfigBuilder) WithCache(cache Cache) *ConfigBuilder

WithCache sets custom cache implementation.

func (*ConfigBuilder) WithCacheBackend

func (b *ConfigBuilder) WithCacheBackend(backend string) *ConfigBuilder

WithCacheBackend sets cache backend.

func (*ConfigBuilder) WithCacheDirectory

func (b *ConfigBuilder) WithCacheDirectory(dir string) *ConfigBuilder

WithCacheDirectory sets filesystem cache directory.

func (*ConfigBuilder) WithCacheTTL

func (b *ConfigBuilder) WithCacheTTL(ttl time.Duration) *ConfigBuilder

WithCacheTTL sets cache TTL.

func (*ConfigBuilder) WithClientAgent

func (b *ConfigBuilder) WithClientAgent(agent string) *ConfigBuilder

WithClientAgent sets client agent name.

func (*ConfigBuilder) WithEnvironmentToken

func (b *ConfigBuilder) WithEnvironmentToken(token string) *ConfigBuilder

WithEnvironmentToken sets the environment token.

func (*ConfigBuilder) WithHTTPClient

func (b *ConfigBuilder) WithHTTPClient(client *http.Client) *ConfigBuilder

WithHTTPClient sets custom http client.

func (*ConfigBuilder) WithLogger

func (b *ConfigBuilder) WithLogger(logger Logger) *ConfigBuilder

WithLogger sets logger.

func (*ConfigBuilder) WithSDKVersion

func (b *ConfigBuilder) WithSDKVersion(version string) *ConfigBuilder

WithSDKVersion sets sdk version string.

func (*ConfigBuilder) WithUsageReporting

func (b *ConfigBuilder) WithUsageReporting(enabled bool) *ConfigBuilder

WithUsageReporting toggles usage reporting.

type ConfigurationError

type ConfigurationError struct {
	Message string
	// contains filtered or unexported fields
}

ConfigurationError indicates invalid SDK configuration.

func (*ConfigurationError) Error

func (e *ConfigurationError) Error() string

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context captures the evaluation context.

func ContextFromData

func ContextFromData(data ContextData) Context

ContextFromData creates context from already-structured data.

func NewContext

func NewContext(typ, identifier, name string, attributes []Attribute) Context

NewContext creates a context.

func SingleContext

func SingleContext(typ, identifier, name string) Context

SingleContext creates a simple context with optional name.

func (*Context) AddAttribute

func (c *Context) AddAttribute(attr Attribute)

AddAttribute adds an attribute to the context.

func (Context) Attributes

func (c Context) Attributes() []ContextAttribute

Attributes returns a copy of all attributes.

func (Context) Data

func (c Context) Data() ContextData

Data returns a copy of context data.

func (Context) GetAttribute

func (c Context) GetAttribute(key string) (ContextAttribute, bool)

GetAttribute retrieves an attribute by key.

func (Context) Identifier

func (c Context) Identifier() string

Identifier returns the context identifier.

func (Context) IsEmpty

func (c Context) IsEmpty() bool

IsEmpty determines whether context has meaningful fields.

func (Context) JSON

func (c Context) JSON() ([]byte, error)

JSON serializes context into API representation.

func (Context) Name

func (c Context) Name() string

Name returns the context name.

func (Context) Type

func (c Context) Type() string

Type returns the context type.

type ContextAttribute

type ContextAttribute struct {
	Key    string         `json:"key"`
	Values []ContextValue `json:"values"`
}

ContextAttribute is an attribute used for context targeting.

type ContextData

type ContextData struct {
	Type       string             `json:"type"`
	Name       string             `json:"name,omitempty"`
	Identifier string             `json:"identifier,omitempty"`
	Attributes []ContextAttribute `json:"attributes,omitempty"`
}

ContextData is the serialized context payload.

type ContextValue

type ContextValue struct {
	Value string `json:"value"`
}

ContextValue is a single context value.

type DefaultsCollection

type DefaultsCollection struct {
	// contains filtered or unexported fields
}

DefaultsCollection stores default values by flag key.

func DefaultsFromMap

func DefaultsFromMap(values map[string]any) *DefaultsCollection

DefaultsFromMap creates defaults from a map.

func NewDefaultsCollection

func NewDefaultsCollection() *DefaultsCollection

NewDefaultsCollection creates an empty defaults collection.

func (*DefaultsCollection) All

func (c *DefaultsCollection) All() map[string]any

All returns a shallow copy.

func (*DefaultsCollection) Clear

func (c *DefaultsCollection) Clear()

Clear removes all entries.

func (*DefaultsCollection) Delete

func (c *DefaultsCollection) Delete(key string)

Delete removes a key.

func (*DefaultsCollection) Get

func (c *DefaultsCollection) Get(key string) (any, bool)

Get gets a default value.

func (*DefaultsCollection) Has

func (c *DefaultsCollection) Has(key string) bool

Has checks if key exists.

func (*DefaultsCollection) Keys

func (c *DefaultsCollection) Keys() []string

Keys returns all keys.

func (*DefaultsCollection) Set

func (c *DefaultsCollection) Set(key string, value any)

Set sets a default value.

func (*DefaultsCollection) Size

func (c *DefaultsCollection) Size() int

Size returns item count.

type Error

type Error interface {
	error
	// contains filtered or unexported methods
}

Error is implemented by every error type this SDK returns, mirroring the shared ZenmanageError base class in the JavaScript, PHP, and Python SDKs. Use errors.As to distinguish SDK errors from other errors:

var zmErr zenmanage.Error
if errors.As(err, &zmErr) { ... }

type EvaluationError

type EvaluationError struct {
	Message string
	// contains filtered or unexported fields
}

EvaluationError indicates a rule or flag evaluation failure.

func (*EvaluationError) Error

func (e *EvaluationError) Error() string

type FetchRulesError

type FetchRulesError struct {
	Message    string
	StatusCode int
	// contains filtered or unexported fields
}

FetchRulesError indicates a failure while loading rules from remote APIs.

func (*FetchRulesError) Error

func (e *FetchRulesError) Error() string

type FileSystemCache

type FileSystemCache struct {
	// contains filtered or unexported fields
}

FileSystemCache stores cache entries on disk.

func NewFileSystemCache

func NewFileSystemCache(dir string) *FileSystemCache

NewFileSystemCache creates a filesystem cache backend.

func (*FileSystemCache) Clear

func (c *FileSystemCache) Clear() error

Clear removes all cache files in the cache directory.

func (*FileSystemCache) Delete

func (c *FileSystemCache) Delete(key string) error

Delete removes a cache entry.

func (*FileSystemCache) Get

func (c *FileSystemCache) Get(key string) (string, bool, error)

Get reads a cache entry from disk.

func (*FileSystemCache) Set

func (c *FileSystemCache) Set(key, value string, ttl time.Duration) error

Set writes a cache entry to disk.

type Flag

type Flag struct {
	// contains filtered or unexported fields
}

Flag is an evaluated flag object with helper accessors.

func (Flag) AsBool

func (f Flag) AsBool() bool

AsBool coerces value to boolean.

func (Flag) AsNumber

func (f Flag) AsNumber() float64

AsNumber coerces value to float64.

func (Flag) AsString

func (f Flag) AsString() string

AsString coerces value to string.

func (Flag) IsEnabled

func (f Flag) IsEnabled() bool

IsEnabled is true when the flag resolves to boolean true.

func (Flag) Key

func (f Flag) Key() string

Key returns flag key.

func (Flag) Name

func (f Flag) Name() string

Name returns display name.

func (Flag) Rollout

func (f Flag) Rollout() *RolloutData

Rollout returns rollout metadata if present.

func (Flag) Rules

func (f Flag) Rules() []Rule

Rules returns the effective rules.

func (Flag) Target

func (f Flag) Target() Target

Target returns raw target.

func (Flag) Type

func (f Flag) Type() FlagType

Type returns flag primitive type.

func (Flag) Value

func (f Flag) Value() any

Value returns the raw typed value.

func (Flag) Version

func (f Flag) Version() string

Version returns flag version.

type FlagData

type FlagData struct {
	Version string       `json:"version"`
	Type    FlagType     `json:"type"`
	Key     string       `json:"key"`
	Name    string       `json:"name"`
	Target  Target       `json:"target"`
	Rules   []Rule       `json:"rules,omitempty"`
	Rollout *RolloutData `json:"rollout,omitempty"`
}

FlagData is the API representation of a flag.

type FlagManager

type FlagManager struct {
	// contains filtered or unexported fields
}

FlagManager handles rule loading and flag evaluation.

func NewFlagManager

func NewFlagManager(apiClient *APIClient, cache Cache, ruleEngine *RuleEngine, cacheTTL time.Duration, logger Logger) *FlagManager

NewFlagManager creates a flag manager.

func (*FlagManager) All

func (m *FlagManager) All(ctx context.Context) ([]Flag, error)

All returns all evaluated flags.

func (*FlagManager) RefreshRules

func (m *FlagManager) RefreshRules(ctx context.Context) error

RefreshRules forces rules refresh from API.

func (*FlagManager) ReportUsage

func (m *FlagManager) ReportUsage(ctx context.Context, key string, defaultValue any) error

ReportUsage manually reports flag usage to the API, using the manager's current context (if any). Single already reports usage automatically on every evaluation; call this directly only when usage needs to be recorded outside of a Single/All evaluation path, matching the explicit reportUsage method exposed by the JavaScript, PHP, and Python SDKs.

func (*FlagManager) Single

func (m *FlagManager) Single(ctx context.Context, key string, inlineDefault ...any) (Flag, error)

Single returns one evaluated flag by key.

func (*FlagManager) WithContext

func (m *FlagManager) WithContext(ctx Context) *FlagManager

WithContext returns a new flag manager that shares rules/cache with the receiver but uses a different context.

func (*FlagManager) WithDefaults

func (m *FlagManager) WithDefaults(defaults *DefaultsCollection) *FlagManager

WithDefaults returns a new flag manager that shares rules/cache with the receiver but uses a different defaults collection.

type FlagType

type FlagType string

FlagType is the primitive type for a flag.

const (
	// FlagTypeBoolean represents boolean flags.
	FlagTypeBoolean FlagType = "boolean"
	// FlagTypeString represents string flags.
	FlagTypeString FlagType = "string"
	// FlagTypeNumber represents numeric flags.
	FlagTypeNumber FlagType = "number"
)

type InMemoryCache

type InMemoryCache struct {
	// contains filtered or unexported fields
}

InMemoryCache is a process-local cache backend.

func NewInMemoryCache

func NewInMemoryCache() *InMemoryCache

NewInMemoryCache creates an in-memory cache.

func (*InMemoryCache) Clear

func (c *InMemoryCache) Clear() error

Clear removes all cache entries.

func (*InMemoryCache) Delete

func (c *InMemoryCache) Delete(key string) error

Delete removes a cache entry.

func (*InMemoryCache) Get

func (c *InMemoryCache) Get(key string) (string, bool, error)

Get retrieves a cache entry if present and unexpired.

func (*InMemoryCache) Set

func (c *InMemoryCache) Set(key, value string, ttl time.Duration) error

Set stores a cache entry.

type InvalidRulesError

type InvalidRulesError struct {
	Message string
	// contains filtered or unexported fields
}

InvalidRulesError indicates malformed or semantically invalid rules payloads.

func (*InvalidRulesError) Error

func (e *InvalidRulesError) Error() string

type Logger

type Logger interface {
	Debug(message string, meta map[string]any)
	Info(message string, meta map[string]any)
	Warn(message string, meta map[string]any)
	Error(message string, meta map[string]any)
}

Logger is the SDK logger contract.

type NullCache

type NullCache struct{}

NullCache is a no-op cache backend.

func NewNullCache

func NewNullCache() *NullCache

NewNullCache creates a null cache.

func (*NullCache) Clear

func (c *NullCache) Clear() error

Clear is a no-op.

func (*NullCache) Delete

func (c *NullCache) Delete(string) error

Delete is a no-op.

func (*NullCache) Get

func (c *NullCache) Get(string) (string, bool, error)

Get always misses.

func (*NullCache) Set

Set is a no-op.

type NullLogger

type NullLogger struct{}

NullLogger is a silent logger.

func (NullLogger) Debug

func (NullLogger) Debug(string, map[string]any)

Debug discards the message.

func (NullLogger) Error

func (NullLogger) Error(string, map[string]any)

Error discards the message.

func (NullLogger) Info

func (NullLogger) Info(string, map[string]any)

Info discards the message.

func (NullLogger) Warn

func (NullLogger) Warn(string, map[string]any)

Warn discards the message.

type RolloutData

type RolloutData struct {
	Target     Target `json:"target"`
	Rules      []Rule `json:"rules"`
	Percentage int    `json:"percentage"`
	Salt       string `json:"salt"`
	Status     string `json:"status"`
}

RolloutData configures percentage rollout behavior for a flag.

type Rule

type Rule struct {
	Version     string          `json:"version,omitempty"`
	Description string          `json:"description,omitempty"`
	Criteria    *RuleCondition  `json:"criteria,omitempty"`
	Clauses     []RuleCondition `json:"clauses,omitempty"`
	Position    int             `json:"position,omitempty"`
	Value       ValueEnvelope   `json:"value"`
}

Rule holds rule criteria and the resulting target value.

type RuleCondition

type RuleCondition struct {
	Attribute string
	Operator  string
	Value     any
}

RuleCondition is a single clause for rule matching.

func (*RuleCondition) UnmarshalJSON

func (rc *RuleCondition) UnmarshalJSON(data []byte) error

UnmarshalJSON maps both the legacy internal format (attribute/operator/value) and the CDN wire format (selector/selector_subtype/comparer/values) to the internal fields used by the rule engine.

type RuleContextTarget

type RuleContextTarget struct {
	Identifier string  `json:"identifier"`
	Type       *string `json:"type,omitempty"`
}

RuleContextTarget is a typed context target used in context/segment clauses.

type RuleEngine

type RuleEngine struct{}

RuleEngine evaluates flag rules against a context.

func NewRuleEngine

func NewRuleEngine() *RuleEngine

NewRuleEngine creates a rule engine.

func (*RuleEngine) Evaluate

func (e *RuleEngine) Evaluate(rules []Rule, context Context) (*ValueEnvelope, error)

Evaluate finds the first matching rule and returns its value envelope.

type RulesResponse

type RulesResponse struct {
	Version string     `json:"version"`
	Flags   []FlagData `json:"flags"`
}

RulesResponse is the top-level rule payload.

type Target

type Target struct {
	Version     string        `json:"version,omitempty"`
	ExpiredAt   string        `json:"expired_at,omitempty"`
	PublishedAt string        `json:"published_at,omitempty"`
	ScheduledAt string        `json:"scheduled_at,omitempty"`
	Value       ValueEnvelope `json:"value"`
}

Target contains a value payload and metadata.

type ValueEnvelope

type ValueEnvelope struct {
	Version string `json:"version,omitempty"`
	Value   struct {
		Boolean *bool    `json:"boolean,omitempty"`
		String  *string  `json:"string,omitempty"`
		Number  *float64 `json:"number,omitempty"`
	} `json:"value"`
}

ValueEnvelope is the nested API value format.

type Zenmanage

type Zenmanage struct {
	// contains filtered or unexported fields
}

Zenmanage is the main SDK entry point.

func New

func New(config Config) *Zenmanage

New creates a Zenmanage SDK instance.

func (*Zenmanage) Flags

func (z *Zenmanage) Flags() *FlagManager

Flags returns the flag manager for advanced use (context, defaults, bulk evaluation).

func (*Zenmanage) GetNumber

func (z *Zenmanage) GetNumber(ctx context.Context, key, userID string, defaultValue float64) (float64, error)

GetNumber returns the numeric value of a flag for the given user ID. defaultValue is returned when the flag is not found.

func (*Zenmanage) GetString

func (z *Zenmanage) GetString(ctx context.Context, key, userID, defaultValue string) (string, error)

GetString returns the string value of a flag for the given user ID. defaultValue is returned when the flag is not found.

func (*Zenmanage) IsEnabled

func (z *Zenmanage) IsEnabled(ctx context.Context, key, userID string) (bool, error)

IsEnabled returns whether a boolean flag is enabled for the given user ID. When userID is non-empty the flag is evaluated against a "user" context so rollout rules and targeting apply. Pass an empty userID to evaluate without context (e.g. kill-switch style flags).

Directories

Path Synopsis
Package examples contains runnable samples demonstrating the Zenmanage Go SDK, mirroring the sample set in the JavaScript and PHP SDKs.
Package examples contains runnable samples demonstrating the Zenmanage Go SDK, mirroring the sample set in the JavaScript and PHP SDKs.
Package middleware provides net/http middleware for the Zenmanage Go SDK.
Package middleware provides net/http middleware for the Zenmanage Go SDK.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL