Documentation
¶
Index ¶
- Constants
- Variables
- func EnqueueWithContext(ctx context.Context, client EnqueueClient, msg Message) error
- func NewRequestContextMiddleware(next http.Handler, opts ...RequestContextOption) http.Handler
- func Ptr[T any](v T) *T
- func SimpleInAppDecider(frame runtime.Frame) bool
- func WithFreshRequestContext(ctx context.Context, requestContext RequestContext) context.Context
- func WithRequestContext(ctx context.Context, requestContext RequestContext) context.Context
- type APIError
- type APIMessage
- type Alias
- type AliasInApi
- type AliasInApiProperties
- type Backoff
- type Callback
- type Capture
- type CaptureInApi
- type Client
- type CommonResponseFields
- type CompressionMode
- type Config
- type ConfigError
- type DecideRequestData
- type DecideResponse
- type DefaultStackTraceExtractor
- type DescriptionExtractor
- type EnqueueClient
- type ErrorExtractor
- type EvaluateFlagsPayload
- type Exception
- type ExceptionInApi
- type ExceptionInApiProperties
- type ExceptionItem
- type ExceptionMechanism
- type ExceptionStacktrace
- type FeatureFlag
- type FeatureFlagCondition
- type FeatureFlagEvaluations
- func (e *FeatureFlagEvaluations) GetFlag(key string) interface{}
- func (e *FeatureFlagEvaluations) GetFlagPayload(key string) string
- func (e *FeatureFlagEvaluations) IsEnabled(key string) bool
- func (e *FeatureFlagEvaluations) Keys() []string
- func (e *FeatureFlagEvaluations) Only(keys []string) *FeatureFlagEvaluations
- func (e *FeatureFlagEvaluations) OnlyAccessed() *FeatureFlagEvaluations
- type FeatureFlagPayload
- type FeatureFlagPayloadNoKey
- type FeatureFlagResult
- type FeatureFlagsPoller
- func (poller *FeatureFlagsPoller) ForceReload()
- func (poller *FeatureFlagsPoller) GetAllFlags(flagConfig FeatureFlagPayloadNoKey) (map[string]interface{}, error)
- func (poller *FeatureFlagsPoller) GetFeatureFlag(flagConfig FeatureFlagPayload) (interface{}, bool, error)
- func (poller *FeatureFlagsPoller) GetFeatureFlagPayload(flagConfig FeatureFlagPayload) (string, error)
- func (poller *FeatureFlagsPoller) GetFeatureFlagWithPayload(flagConfig FeatureFlagPayload) flagValueAndPayload
- func (poller *FeatureFlagsPoller) GetFeatureFlags() ([]FeatureFlag, error)
- type FeatureFlagsResponse
- type FieldError
- type Filter
- type FlagDetail
- type FlagMetadata
- type FlagProperty
- type FlagReason
- type FlagVariant
- type FlagVariantMeta
- type FlagsRequestData
- type FlagsResponse
- type GroupIdentify
- type GroupIdentifyInApi
- type Groups
- type Identify
- type IdentifyInApi
- type InAppDecider
- type InconclusiveMatchError
- type Logger
- type Message
- type Properties
- type PropertyGroup
- type RequestContext
- type RequestContextOption
- type RequestContextOptions
- type RequiresServerEvaluationError
- type SendFeatureFlagsBool
- type SendFeatureFlagsOptions
- type SendFeatureFlagsValue
- type SlogCaptureHandler
- type SlogOption
- func WithDescriptionExtractor(extractor DescriptionExtractor) SlogOption
- func WithDistinctIDFn(fn func(ctx context.Context, r slog.Record) string) SlogOption
- func WithFingerprintFn(fn func(ctx context.Context, r slog.Record) *string) SlogOption
- func WithMinCaptureLevel(l slog.Level) SlogOption
- func WithPropertiesFn(fn func(ctx context.Context, r slog.Record) Properties) SlogOption
- func WithSkip(n int) SlogOption
- func WithStackTraceExtractor(extractor StackTraceExtractor) SlogOption
- type StackFrame
- type StackTraceExtractor
- type Ticker
- type Variants
Examples ¶
Constants ¶
const ( // SDKName is the library identifier sent in event metadata. SDKName = "posthog-go" // DefaultEndpoint is the default PostHog API host used when Config.Endpoint is empty. DefaultEndpoint = "https://us.i.posthog.com" // DefaultInterval is the default flush interval used when Config.Interval is zero. DefaultInterval = 5 * time.Second // DefaultFeatureFlagsPollingInterval is the default local feature flag reload interval. DefaultFeatureFlagsPollingInterval = 5 * time.Minute // DefaultFeatureFlagRequestTimeout is the default timeout for feature flag requests. DefaultFeatureFlagRequestTimeout = 3 * time.Second // DefaultBatchSize is the default batch size used when Config.BatchSize is zero. DefaultBatchSize = 250 // DefaultBatchUploadTimeout is the default timeout for uploading batched // events to the /batch/ endpoint. DefaultBatchUploadTimeout = 10 * time.Second // DefaultBatchSubmitTimeout is the default timeout for submitting batches // to the worker pool when the queue is full. This allows workers time to // complete during transient latency spikes, reducing unnecessary data loss. DefaultBatchSubmitTimeout = 100 * time.Millisecond // DefaultMaxEnqueuedRequests is the default maximum number of batches that // can be queued for sending. DefaultMaxEnqueuedRequests = 1000 )
const ( // FeatureFlagErrorErrorsWhileComputing indicates the server returned errorsWhileComputingFlags=true FeatureFlagErrorErrorsWhileComputing = "errors_while_computing_flags" // FeatureFlagErrorFlagMissing indicates the requested flag was not in the API response FeatureFlagErrorFlagMissing = "flag_missing" // FeatureFlagErrorEvaluationFailed indicates the flag was present but failed to evaluate due to a transient server error FeatureFlagErrorEvaluationFailed = "evaluation_failed" // FeatureFlagErrorQuotaLimited indicates rate/quota limit was exceeded FeatureFlagErrorQuotaLimited = "quota_limited" // FeatureFlagErrorTimeout indicates request timed out FeatureFlagErrorTimeout = "timeout" // FeatureFlagErrorConnectionError indicates network connectivity issue FeatureFlagErrorConnectionError = "connection_error" // FeatureFlagErrorUnknownError indicates an unexpected error occurred FeatureFlagErrorUnknownError = "unknown_error" // FeatureFlagErrorAPIErrorPrefix is the prefix for API errors with status codes FeatureFlagErrorAPIErrorPrefix = "api_error_" )
Feature flag error type constants for the $feature_flag_error property. These values are sent in analytics events to track flag evaluation failures. They should not be changed without considering impact on existing dashboards and queries that filter on these values.
const ( // CACHE_DEFAULT_SIZE is the number of feature flag calls tracked for local deduplication. CACHE_DEFAULT_SIZE = 300_000 // DefaultIdleConns is the default max idle connections for the HTTP client. DefaultIdleConns = 100 // DefaultIdleConnsPerHost is the default max idle connections per host. // This is higher than http.DefaultTransport's value of 2 to reduce // connection churn when sending batches. DefaultIdleConnsPerHost = 10 )
const ( // HeaderPostHogDistinctID is the HTTP header used to propagate a PostHog distinct ID. HeaderPostHogDistinctID = "X-PostHog-Distinct-Id" // HeaderPostHogSessionID is the HTTP header used to propagate a PostHog session ID. HeaderPostHogSessionID = "X-PostHog-Session-Id" )
const (
// LONG_SCALE is the denominator used to normalize feature flag hash values.
LONG_SCALE = 0xfffffffffffffff
)
const Version = "1.13.1"
Version of the client.
Variables ¶
var ( // This error is returned by methods of the `Client` interface when they are // called after the client was already closed. ErrClosed = errors.New("the client was already closed") // This error is used to notify the application that too many requests are // already being sent and no more messages can be accepted. ErrTooManyRequests = errors.New("too many requests are already in-flight") // This error is used to notify the client callbacks that a message send // failed because the JSON representation of a message exceeded the upper // limit. ErrMessageTooBig = errors.New("the message exceeds the maximum allowed size") // ErrNoPersonalAPIKey is returned when PersonalApiKey is required for the // requested operation but was not configured. ErrNoPersonalAPIKey = errors.New("no PersonalAPIKey provided") // ErrNoDistinctID is returned when distinct_id is required for the requested // operation but was not provided. ErrNoDistinctID = errors.New("no distinct_id provided") // ErrSDKDisabled is returned when the SDK is disabled because the project API key is missing. ErrSDKDisabled = errors.New("posthog SDK is disabled because project API key is missing") )
var ErrFlagNotFound = errors.New("feature flag not found")
ErrFlagNotFound is returned when a feature flag does not exist or is disabled. Use errors.Is(err, ErrFlagNotFound) to check for this error.
Functions ¶
func EnqueueWithContext ¶ added in v1.13.0
func EnqueueWithContext(ctx context.Context, client EnqueueClient, msg Message) error
EnqueueWithContext queues a message and applies any PostHog request context attached to ctx. Use this from HTTP handlers with r.Context() when NewRequestContextMiddleware is installed.
func NewRequestContextMiddleware ¶ added in v1.13.0
func NewRequestContextMiddleware(next http.Handler, opts ...RequestContextOption) http.Handler
NewRequestContextMiddleware wraps an http.Handler with PostHog request-context extraction.
The middleware always attaches safe request metadata to r.Context(). By default it also reads X-PostHog-Distinct-Id and X-PostHog-Session-Id into request-scoped analytics context. Use EnqueueWithContext(r.Context(), ...) for captures inside the request so this metadata is applied.
func SimpleInAppDecider ¶ added in v1.6.7
SimpleInAppDecider is a basic InAppDecider that classifies frames by file path. It excludes vendored modules, module cache paths, and Go toolchain paths.
func WithFreshRequestContext ¶ added in v1.13.0
func WithFreshRequestContext(ctx context.Context, requestContext RequestContext) context.Context
WithFreshRequestContext returns a child context with PostHog request metadata attached without inheriting any existing PostHog request context from the parent.
func WithRequestContext ¶ added in v1.13.0
func WithRequestContext(ctx context.Context, requestContext RequestContext) context.Context
WithRequestContext returns a child context with PostHog request metadata attached. Existing PostHog request context values are inherited: non-empty DistinctId and SessionId override the parent values, and Properties are merged with child properties taking precedence.
Types ¶
type APIError ¶ added in v1.9.0
type APIError struct {
// StatusCode is the HTTP status code returned by the PostHog API.
StatusCode int
// Message is the error message returned by or derived from the API response.
Message string
}
APIError represents an HTTP API error with a status code. This allows classifyError to generate api_error_{status} strings.
func NewAPIError ¶ added in v1.9.0
NewAPIError creates an APIError with the given HTTP status code and message.
type APIMessage ¶
type APIMessage interface{}
APIMessage is a wire-format message produced by Message.APIfy and passed to callbacks.
type Alias ¶
type Alias struct {
// Type is reserved for SDK serialization and is overwritten by Enqueue.
Type string
// Uuid is an optional event UUID. If empty, Enqueue generates a random UUID.
Uuid string
// Alias is the alternate distinct ID to attach to DistinctId.
Alias string
// DistinctId is the existing user distinct ID that Alias should resolve to.
DistinctId string
// Timestamp is the event timestamp. If zero, Enqueue uses the current time.
Timestamp time.Time
// DisableGeoIP controls whether this alias event disables GeoIP lookup.
// Enqueue overwrites it from Config.GetDisableGeoIP.
DisableGeoIP bool
}
Alias represents an alias call that links another distinct ID to an existing user. Enqueue validates that DistinctId and Alias are both set, fills Type, Uuid, Timestamp, and DisableGeoIP, then sends the message as a $create_alias event.
func (Alias) APIfy ¶
func (msg Alias) APIfy() APIMessage
APIfy converts an Alias message into the PostHog batch API representation.
type AliasInApi ¶
type AliasInApi struct {
// Type is the message type sent to the batch API.
Type string `json:"type"`
// Uuid is the event UUID sent to the batch API.
Uuid string `json:"uuid"`
// Library is the SDK name sent to the batch API.
Library string `json:"library"`
// LibraryVersion is the SDK version sent to the batch API.
LibraryVersion string `json:"library_version"`
// Timestamp is the event timestamp sent to the batch API.
Timestamp time.Time `json:"timestamp"`
// Properties contains alias-specific event properties.
Properties AliasInApiProperties `json:"properties"`
// Event is always $create_alias for Alias messages.
Event string `json:"event"`
}
AliasInApi is the wire-format payload produced from an Alias message.
type AliasInApiProperties ¶
type AliasInApiProperties struct {
// DistinctId is the canonical user distinct ID.
DistinctId string `json:"distinct_id"`
// Alias is the alternate distinct ID being linked to DistinctId.
Alias string `json:"alias"`
// Lib is the SDK name sent as $lib.
Lib string `json:"$lib"`
// LibVersion is the SDK version sent as $lib_version.
LibVersion string `json:"$lib_version"`
// DisableGeoIP is sent as $geoip_disable when GeoIP lookup is disabled.
DisableGeoIP bool `json:"$geoip_disable,omitempty"`
// contains filtered or unexported fields
}
AliasInApiProperties is the wire-format properties object for an Alias message.
func (AliasInApiProperties) ToProperties ¶ added in v1.11.2
func (ctx AliasInApiProperties) ToProperties() Properties
type Backoff ¶ added in v1.8.0
type Backoff struct {
// contains filtered or unexported fields
}
Backoff calculates exponential retry delays with optional jitter and a maximum cap.
func DefaultBackoff ¶ added in v1.8.0
func DefaultBackoff() *Backoff
DefaultBackoff creates a Backoff with the SDK's default retry policy:
base: 100 milliseconds factor: 2 jitter: 0 cap: 10 seconds
func NewBackoff ¶ added in v1.8.0
NewBackoff creates a Backoff with the provided base duration, exponential factor, jitter ratio, and maximum cap duration.
func (*Backoff) Duration ¶ added in v1.8.0
Duration returns the backoff interval for the given attempt.
type Callback ¶
type Callback interface {
// Success is called for every message that was successfully sent to the API.
Success(APIMessage)
// Failure is called for every message that failed to be sent to the API and
// will be discarded by the client. The error describes the send or serialization failure.
Failure(APIMessage, error)
}
Callback is implemented by applications that want delivery notifications.
Callback methods are called by a client's internal goroutines. There are no guarantees about which goroutine triggers the callbacks, whether calls are made sequentially or in parallel, or whether callback order matches enqueue order.
Callback methods must return quickly and avoid long blocking operations so they do not interfere with the client's internal workflow.
type Capture ¶
type Capture struct {
// Type is reserved for SDK serialization and is overwritten by Enqueue.
Type string
// Uuid is an optional event UUID. If empty, Enqueue generates a random UUID.
// Set it only when you need idempotency, for example to prevent duplicate events.
Uuid string
// DistinctId identifies the user or entity that performed Event.
// When using EnqueueWithContext, this can be inherited from RequestContext.
DistinctId string
// Event is the event name to capture. It must be non-empty.
Event string
// Timestamp is the event timestamp. If zero, Enqueue uses the current time.
Timestamp time.Time
// Properties are event properties. Enqueue merges request context properties
// and Config.DefaultEventProperties into this map before sending.
Properties Properties
// Groups associates the event with group analytics groups.
Groups Groups
// SendFeatureFlags requests legacy feature flag enrichment on this event.
// Deprecated: Prefer Client.EvaluateFlags and pass the returned snapshot via Flags.
SendFeatureFlags SendFeatureFlagsValue
// Flags, when set, attaches $feature/<key> and $active_feature_flags
// properties from a snapshot returned by Client.EvaluateFlags. It is
// preferred over SendFeatureFlags: the snapshot guarantees the event
// carries the exact values the application branched on and avoids a
// hidden /flags request on every capture. Flags takes precedence when
// both are set.
Flags *FeatureFlagEvaluations
}
Capture represents a custom event to send to PostHog. Enqueue validates Event and DistinctId (or obtains DistinctId from request context), fills Type, Uuid, and Timestamp, merges Config.DefaultEventProperties, and queues the event for a future batch upload.
Example ¶
body, server := mockServer()
defer server.Close()
client, _ := NewWithConfig("Csyjlnlun3OzyNJAafdlv", Config{
Endpoint: server.URL,
BatchSize: 1,
now: mockTime,
})
defer client.Close()
client.Enqueue(Capture{
Uuid: "00000000-0000-0000-0000-000000000000",
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"version": "1.0.0",
},
SendFeatureFlags: SendFeatureFlags(false),
})
fmt.Printf("%s\n", <-body)
func (Capture) APIfy ¶
func (msg Capture) APIfy() APIMessage
APIfy converts a Capture message into the PostHog batch API representation.
type CaptureInApi ¶
type CaptureInApi struct {
// Type is the message type sent to the batch API.
Type string `json:"type"`
// Uuid is the event UUID sent to the batch API.
Uuid string `json:"uuid"`
// Library is the SDK name sent to the batch API.
Library string `json:"library"`
// LibraryVersion is the SDK version sent to the batch API.
LibraryVersion string `json:"library_version"`
// Timestamp is the event timestamp sent to the batch API.
Timestamp time.Time `json:"timestamp"`
// DistinctId identifies the user or entity for the event.
DistinctId string `json:"distinct_id"`
// Event is the captured event name.
Event string `json:"event"`
// Properties contains event, SDK, system, group, and feature flag properties.
Properties Properties `json:"properties"`
// SendFeatureFlags carries the legacy send_feature_flags value for compatibility.
SendFeatureFlags SendFeatureFlagsValue `json:"send_feature_flags"`
}
CaptureInApi is the wire-format payload produced from a Capture message.
type Client ¶
type Client interface {
EnqueueClient
// Close gracefully shuts down the client and flushes pending messages.
// If Config.ShutdownTimeout is positive, Close uses it as the shutdown deadline;
// otherwise it waits indefinitely. Repeated calls return ErrClosed.
Close() error
// IsFeatureEnabled evaluates one feature flag for a user and returns the same
// value as GetFeatureFlag: a variant string for multivariate flags or a bool
// for boolean flags. The FeatureFlagPayload parameter supplies the flag key,
// distinct ID, optional groups/properties, and evaluation options.
// Deprecated: Prefer EvaluateFlags for new code.
IsFeatureEnabled(FeatureFlagPayload) (interface{}, error)
// GetFeatureFlag evaluates one feature flag for a user. It returns a variant
// string for multivariate flags, true or false for boolean flags, false with
// nil error when the flag is missing/disabled, and an error for evaluation failures.
// Deprecated: Prefer EvaluateFlags for new code.
GetFeatureFlag(FeatureFlagPayload) (interface{}, error)
// GetFeatureFlagResult evaluates one feature flag and returns its value and payload together.
// Use this instead of calling GetFeatureFlag and GetFeatureFlagPayload separately.
// It returns ErrFlagNotFound when the flag cannot be found or evaluated and
// ErrNoPersonalAPIKey when OnlyEvaluateLocally is true without PersonalApiKey.
GetFeatureFlagResult(FeatureFlagPayload) (*FeatureFlagResult, error)
// GetFeatureFlagPayload returns the payload for the matching flag value, or an
// empty string when no payload is configured or the flag is missing/disabled.
// Deprecated: Use GetFeatureFlagResult instead, which returns both the flag value
// and payload while properly tracking feature flag usage.
GetFeatureFlagPayload(FeatureFlagPayload) (string, error)
// GetRemoteConfigPayload returns the decrypted payload for a remote config flag key.
// It requires Config.PersonalApiKey and returns ErrNoPersonalAPIKey when missing.
GetRemoteConfigPayload(string) (string, error)
// GetAllFlags evaluates all flags for a user. Returned values are booleans for
// boolean flags and strings for multivariate variants. It returns ErrNoPersonalAPIKey
// when OnlyEvaluateLocally is true without PersonalApiKey.
GetAllFlags(FeatureFlagPayloadNoKey) (map[string]interface{}, error)
// EvaluateFlags returns a snapshot of feature-flag evaluations for the
// given distinct_id using at most one /flags request. Returns ErrNoDistinctID
// if DistinctId is empty. Pass the returned snapshot to a Capture event via
// Capture.Flags to attach $feature/<key> properties without another network call.
// Calls to IsEnabled and GetFlag
// on the snapshot fire deduped $feature_flag_called events; GetFlagPayload
// does not.
//
// If the remote /flags request fails after some flags were resolved
// locally, EvaluateFlags returns a non-nil snapshot containing the
// locally-evaluated flags alongside the error so the caller can still
// branch on what was resolved.
// If OnlyEvaluateLocally is true and no PersonalApiKey is configured, returns ErrNoPersonalAPIKey.
EvaluateFlags(EvaluateFlagsPayload) (*FeatureFlagEvaluations, error)
// ReloadFeatureFlags forces a reload of feature flags.
// If no PersonalApiKey is configured, returns ErrNoPersonalAPIKey.
ReloadFeatureFlags() error
// CloseWithContext gracefully shuts down the client with the provided context.
// The context can be used to control the shutdown deadline.
CloseWithContext(context.Context) error
}
Client interface is the main API exposed by the posthog package. Values that satisfy this interface are returned by the client constructors provided by the package and provide a way to send messages via the HTTP API.
func New ¶
New creates a Client with the default Config and the provided PostHog project API key.
The apiKey parameter is trimmed before use. If it is empty, New returns a no-op client whose methods return default values and ErrSDKDisabled where applicable.
func NewWithConfig ¶
NewWithConfig creates a Client with the provided PostHog project API key and Config.
The apiKey, Config.Endpoint, and Config.PersonalApiKey values are trimmed before use. It returns a ConfigError when config contains invalid values such as negative intervals or out-of-range retry settings; in that case the returned Client is nil. If apiKey is empty after trimming, NewWithConfig returns a no-op client and nil error.
type CommonResponseFields ¶ added in v1.4.6
type CommonResponseFields struct {
// QuotaLimited lists quota-limited resources returned by the API.
QuotaLimited []string `json:"quota_limited"`
// RequestId is the API request identifier for tracing flag evaluation.
RequestId string `json:"requestId"`
// EvaluatedAt is the server evaluation timestamp, when returned.
EvaluatedAt *int64 `json:"evaluatedAt"`
// ErrorsWhileComputingFlags reports whether the server had errors computing any flags.
ErrorsWhileComputingFlags bool `json:"errorsWhileComputingFlags"`
}
CommonResponseFields contains fields common to all flags response versions.
type CompressionMode ¶ added in v1.9.1
type CompressionMode uint8
CompressionMode specifies the compression algorithm for batch payloads.
const ( // CompressionNone disables compression (default). CompressionNone CompressionMode = 0 // CompressionGzip enables GZIP compression for batch payloads. CompressionGzip CompressionMode = 1 )
type Config ¶
type Config struct {
// Endpoint is the PostHog API host used for event ingestion and feature flag requests.
// If empty, it defaults to DefaultEndpoint.
Endpoint string
// PersonalApiKey enables local feature flag evaluation, remote config payloads,
// and lower-latency flag APIs. If empty, feature flag methods fall back to the
// /flags endpoint unless the method requires local-only behavior.
// See https://posthog.com/docs/api/overview for how to create a personal API key.
PersonalApiKey string
// DisableGeoIP controls whether event and feature flag requests include
// $geoip_disable/geoip_disable. Nil defaults to true because this SDK usually
// runs server-side; set Ptr(false) to allow GeoIP lookup.
DisableGeoIP *bool
// Interval is the flush interval for queued messages. Messages are sent when
// BatchSize is reached or when this timer fires. If zero, it defaults to
// DefaultInterval.
Interval time.Duration
// DefaultFeatureFlagsPollingInterval is the interval for reloading local feature
// flag definitions when PersonalApiKey is configured. If zero, it defaults to
// DefaultFeatureFlagsPollingInterval.
DefaultFeatureFlagsPollingInterval time.Duration
// FeatureFlagRequestTimeout is the timeout for feature flag and remote config
// HTTP requests. If zero, it defaults to DefaultFeatureFlagRequestTimeout.
// Use time.Duration values such as 3 * time.Second.
FeatureFlagRequestTimeout time.Duration
// NextFeatureFlagsPollingTick optionally calculates the next local feature flag
// polling delay. When set, it overrides DefaultFeatureFlagsPollingInterval.
NextFeatureFlagsPollingTick func() time.Duration
// HistoricalMigration marks captured batches as historical migration traffic.
// See https://posthog.com/docs/migrate for migration guidance.
HistoricalMigration bool
// Transport is the HTTP transport used by the client. Set it to customize
// low-level request behavior such as connection pooling or proxies. If nil,
// the client uses a clone of http.DefaultTransport with SDK defaults.
Transport http.RoundTripper
// Logger receives informational, warning, and error messages from background
// operations. If nil, the client logs to os.Stderr with the standard logger.
Logger Logger
// DefaultEventProperties are merged into every Capture event before sending.
// They are useful for common metadata like service name or app version. On key
// conflicts, values from DefaultEventProperties overwrite event properties.
DefaultEventProperties Properties
// Callback receives success or failure notifications for messages sent to the
// PostHog batch API.
Callback Callback
// BatchSize is the maximum number of messages sent in one batch API call.
// Messages are sent when BatchSize is reached or when Interval fires. If zero,
// it defaults to DefaultBatchSize. The API still enforces a 500KB request limit.
BatchSize int
// Verbose enables more frequent and detailed debug logging through Logger.
Verbose bool
// RetryAfter returns the delay before retrying a failed batch upload. The int
// argument is the retry attempt number. If nil, DefaultBackoff().Duration is used.
RetryAfter func(int) time.Duration
// MaxRetries is the maximum number of retries after the first send attempt.
// It must be in [0,9]. If nil, it defaults to 9 retries (10 total attempts).
MaxRetries *int
// ShutdownTimeout is the maximum time Close waits for in-flight messages to be
// sent. If zero or negative, Close waits indefinitely for backward compatibility.
ShutdownTimeout time.Duration
// BatchUploadTimeout is the timeout for uploading one batch to the /batch/
// endpoint. If zero, it defaults to DefaultBatchUploadTimeout.
BatchUploadTimeout time.Duration
// BatchSubmitTimeout is the maximum time to wait when submitting a batch to the
// worker pool while its queue is full. If zero, it defaults to
// DefaultBatchSubmitTimeout. Set a negative duration for non-blocking behavior
// that drops immediately when the queue is full.
BatchSubmitTimeout time.Duration
// MaxEnqueuedRequests is the maximum number of batches waiting for upload.
// When the queue is full, new batches are dropped and the failure callback is
// invoked. If zero, it defaults to DefaultMaxEnqueuedRequests.
MaxEnqueuedRequests int
// Compression selects the compression mode for batch payloads. CompressionGzip
// compresses payloads and adds the appropriate headers/query params. If zero,
// it defaults to CompressionNone.
Compression CompressionMode
// contains filtered or unexported fields
}
Config carries configuration options used when constructing a Client with NewWithConfig.
Each exported field's zero value is either meaningful or replaced by the default documented on that field.
func (Config) GetDisableGeoIP ¶ added in v1.5.8
GetDisableGeoIP instructs the client to set $geoip_disable on event properties or feature flag requests. It is on by default as Go is mainly used on server side and to be compatible with posthog-python.
type ConfigError ¶
type ConfigError struct {
// A human-readable message explaining why the configuration field's value
// is invalid.
Reason string
// The name of the configuration field that was carrying an invalid value.
Field string
// The value of the configuration field that caused the error.
Value interface{}
}
ConfigError is returned by NewWithConfig when a Config field has an invalid value.
func (ConfigError) Error ¶
func (e ConfigError) Error() string
Error returns a human-readable configuration error message.
type DecideRequestData ¶
type DecideRequestData struct {
// ApiKey is the PostHog project API key.
ApiKey string `json:"api_key"`
// DistinctId is the user distinct ID to evaluate flags for.
DistinctId string `json:"distinct_id"`
// Groups contains group identifiers for group-targeted flags.
Groups Groups `json:"groups"`
// PersonProperties overrides person properties for this evaluation.
PersonProperties Properties `json:"person_properties"`
// GroupProperties overrides group properties for this evaluation, keyed by group type.
GroupProperties map[string]Properties `json:"group_properties"`
}
DecideRequestData is the legacy wire-format request body for flag decide calls.
type DecideResponse ¶
type DecideResponse struct {
// FeatureFlags contains evaluated flag values keyed by flag key.
FeatureFlags map[string]interface{} `json:"featureFlags"`
// FeatureFlagPayloads contains raw payloads keyed by flag key.
FeatureFlagPayloads map[string]json.RawMessage `json:"featureFlagPayloads"`
}
DecideResponse is the legacy wire-format response body for flag decide calls.
type DefaultStackTraceExtractor ¶ added in v1.6.7
type DefaultStackTraceExtractor struct {
// InAppDecider decides whether each runtime frame is application code.
// Set it to SimpleInAppDecider or another non-nil function before use.
InAppDecider InAppDecider
}
DefaultStackTraceExtractor is provided by default as a sane / simple implementation of a StackTraceExtractor. It should be enough for most use cases, however, you're free to create your own implementation if you require more flexibility.
func (DefaultStackTraceExtractor) GetStackTrace ¶ added in v1.6.7
func (d DefaultStackTraceExtractor) GetStackTrace(skip int) *ExceptionStacktrace
GetStackTrace captures the current goroutine stack and converts it to an ExceptionStacktrace. The skip parameter omits leading runtime.Callers frames before conversion.
type DescriptionExtractor ¶ added in v1.6.7
type DescriptionExtractor interface {
// ExtractDescription returns the ExceptionItem.Value to use for a slog record.
ExtractDescription(r slog.Record) string
}
DescriptionExtractor defines the interface for extracting a human-readable description from a slog.Record for use in exception capture.
Implementations should always return a non-empty string; returning an empty string will prevent the error from being captured.
type EnqueueClient ¶ added in v1.6.7
type EnqueueClient interface {
// Enqueue queues a message to be sent by the client when the conditions for a batch
// upload are met.
// This is the main method you'll be using, a typical flow would look like
// this:
//
// client := posthog.New(apiKey)
// ...
// client.Enqueue(posthog.Capture{ ... })
// ...
// client.Close()
//
// Enqueue returns an error if the message could not be queued, which happens
// when the client is closed or the message is invalid.
Enqueue(Message) error
}
EnqueueClient is the minimal interface implemented by clients that can queue PostHog messages.
type ErrorExtractor ¶ added in v1.6.7
type ErrorExtractor struct {
// ErrorKeys are attribute keys to inspect for error values, case-insensitively.
ErrorKeys []string
// Fallback is returned when no matching error attribute is found.
Fallback string
}
ErrorExtractor implements DescriptionExtractor by scanning a slog.Record for attributes containing an error.
ErrorKeys specifies the list of attribute keys (case-insensitive) to check. The first matching attribute with an error value is returned as the description. If no matching error is found, the Fallback is returned.
func (ErrorExtractor) ExtractDescription ¶ added in v1.6.7
func (e ErrorExtractor) ExtractDescription(r slog.Record) string
ExtractDescription returns the first matching error string from the slog record or Fallback.
type EvaluateFlagsPayload ¶ added in v1.12.5
type EvaluateFlagsPayload struct {
// DistinctId is the user distinct ID to evaluate flags for. It is required
// unless EvaluateFlagsWithContext can read one from RequestContext.
DistinctId string
// DeviceId optionally provides a device_id for remote /flags requests and event deduplication.
DeviceId *string
// Groups supplies group identifiers for group-targeted flags.
Groups Groups
// PersonProperties overrides person properties used during flag evaluation.
PersonProperties Properties
// GroupProperties overrides group properties used during flag evaluation, keyed by group type.
GroupProperties map[string]Properties
// OnlyEvaluateLocally prevents fallback to remote /flags requests.
OnlyEvaluateLocally bool
// DisableGeoIP, when non-nil, overrides the client-level DisableGeoIP for
// this evaluation only.
DisableGeoIP *bool
// FlagKeys, when non-empty, trims the network call by asking the server
// to evaluate only the named flags (sent as flag_keys_to_evaluate).
// This is server-side filtering; use FeatureFlagEvaluations.Only to do
// client-side filtering of which flags are attached to events from an
// existing snapshot.
FlagKeys []string
}
EvaluateFlagsPayload is the input to Client.EvaluateFlags.
type Exception ¶ added in v1.6.7
type Exception struct {
// Type is reserved for SDK serialization and is overwritten by Enqueue.
Type string
// Uuid is an optional event UUID. If empty, Enqueue generates a random UUID.
Uuid string
// DistinctId identifies the user or entity associated with the exception.
// When using EnqueueWithContext, this can be inherited from RequestContext.
DistinctId string
// Timestamp is the event timestamp. If zero, Enqueue uses the current time.
Timestamp time.Time
// Properties are custom event properties flattened into the exception event.
Properties Properties
// DisableGeoIP controls whether this exception event disables GeoIP lookup.
// Enqueue overwrites it from Config.GetDisableGeoIP.
DisableGeoIP bool
// ExceptionList is the list of exception items sent as $exception_list. It must be non-empty.
ExceptionList []ExceptionItem
// ExceptionFingerprint optionally overrides PostHog's default exception grouping fingerprint.
ExceptionFingerprint *string
}
Exception represents an error tracking exception event. Enqueue validates DistinctId and ExceptionList (or obtains DistinctId from request context), fills Type, Uuid, Timestamp, and DisableGeoIP, then sends the message as a $exception event.
func NewDefaultException ¶ added in v1.6.7
NewDefaultException builds an Exception with a default stack trace.
The timestamp parameter becomes Exception.Timestamp, distinctID becomes Exception.DistinctId, title becomes the first ExceptionItem.Type, and description becomes the first ExceptionItem.Value. The returned Exception is ready to pass to Client.Enqueue. Build Exception manually if you need custom properties, fingerprints, mechanisms, or stack frames.
func (Exception) APIfy ¶ added in v1.6.7
func (msg Exception) APIfy() APIMessage
APIfy converts an Exception message into the PostHog batch API representation.
type ExceptionInApi ¶ added in v1.6.7
type ExceptionInApi struct {
// Type is the message type sent to the batch API.
Type string `json:"type"`
// Uuid is the event UUID sent to the batch API.
Uuid string `json:"uuid"`
// Library is the SDK name sent to the batch API.
Library string `json:"library"`
// LibraryVersion is the SDK version sent to the batch API.
LibraryVersion string `json:"library_version"`
// Timestamp is the event timestamp sent to the batch API.
Timestamp time.Time `json:"timestamp"`
// Event is always $exception for Exception messages.
Event string `json:"event"`
// Properties contains built-in and custom exception properties.
Properties ExceptionInApiProperties `json:"properties"`
}
ExceptionInApi is the wire-format payload produced from an Exception message.
type ExceptionInApiProperties ¶ added in v1.6.7
type ExceptionInApiProperties struct {
// Lib is the SDK name sent as $lib.
Lib string `json:"$lib"`
// LibVersion is the SDK version sent as $lib_version.
LibVersion string `json:"$lib_version"`
// DistinctId is the user distinct ID associated with the exception.
DistinctId string `json:"distinct_id"`
// DisableGeoIP is sent as $geoip_disable when GeoIP lookup is disabled.
DisableGeoIP bool `json:"$geoip_disable,omitempty"`
// ExceptionList is sent as $exception_list.
ExceptionList []ExceptionItem `json:"$exception_list"`
// ExceptionFingerprint is sent as $exception_fingerprint when provided.
ExceptionFingerprint *string `json:"$exception_fingerprint,omitempty"`
// Custom is flattened into the wire "properties" on marshal.
// Typed fields win on collision.
Custom Properties `json:"-"`
// contains filtered or unexported fields
}
ExceptionInApiProperties is the wire-format properties object for an Exception message.
func (ExceptionInApiProperties) MarshalJSON ¶ added in v1.12.0
func (p ExceptionInApiProperties) MarshalJSON() ([]byte, error)
MarshalJSON lets users add extra keys (via Custom) to the event's JSON output next to the built-in ones like $lib and distinct_id. If a custom key clashes with a built-in, we keep ours and drop theirs.
func (ExceptionInApiProperties) ToProperties ¶ added in v1.11.2
func (ctx ExceptionInApiProperties) ToProperties() Properties
type ExceptionItem ¶ added in v1.6.7
type ExceptionItem struct {
// Type is rendered as the exception title in the PostHog UI.
Type string `json:"type"`
// Value is rendered as the exception description in the PostHog UI.
Value string `json:"value"`
// Mechanism describes how the exception was produced or handled.
Mechanism *ExceptionMechanism `json:"mechanism,omitempty"`
// Stacktrace contains stack frames for the exception. Use StackTraceExtractor to generate it.
Stacktrace *ExceptionStacktrace `json:"stacktrace,omitempty"`
}
ExceptionItem describes one exception in an Exception event.
func (ExceptionItem) Validate ¶ added in v1.6.7
func (msg ExceptionItem) Validate() error
Validate checks that the exception item has Type and Value set.
type ExceptionMechanism ¶ added in v1.6.7
type ExceptionMechanism struct {
// Handled reports whether the exception was handled by application code.
Handled *bool `json:"handled,omitempty"`
// Synthetic reports whether the exception was synthesized by instrumentation.
Synthetic *bool `json:"synthetic,omitempty"`
}
ExceptionMechanism describes whether an exception was handled or synthesized.
type ExceptionStacktrace ¶ added in v1.6.7
type ExceptionStacktrace struct {
// Type is the stack trace representation type. The default extractor uses "raw".
Type string `json:"type"`
// Frames is the ordered list of stack frames.
Frames []StackFrame `json:"frames"`
}
ExceptionStacktrace is a PostHog-compatible stack trace.
type FeatureFlag ¶
type FeatureFlag struct {
// Key is the feature flag key.
Key string `json:"key"`
// RolloutPercentage is the top-level rollout percentage, when configured.
RolloutPercentage *float64 `json:"rollout_percentage"`
// Active reports whether the flag is active.
Active bool `json:"active"`
// Filters contains matching conditions, variants, and payloads.
Filters Filter `json:"filters"`
// EnsureExperienceContinuity indicates that the flag requires server-side continuity checks.
EnsureExperienceContinuity *bool `json:"ensure_experience_continuity"`
// BucketingIdentifier optionally selects the property used for hash bucketing.
BucketingIdentifier *string `json:"bucketing_identifier"`
}
FeatureFlag is a feature flag definition returned by the local evaluation endpoint.
type FeatureFlagCondition ¶
type FeatureFlagCondition struct {
// Properties are the targeting rules in this condition group.
Properties []FlagProperty `json:"properties"`
// RolloutPercentage is the rollout percentage for this condition group.
RolloutPercentage *float64 `json:"rollout_percentage"`
// Variant is the variant key forced by this condition group, when any.
Variant *string `json:"variant"`
// AggregationGroupTypeIndex identifies the group type for this condition group.
AggregationGroupTypeIndex *uint8 `json:"aggregation_group_type_index"`
}
FeatureFlagCondition describes one condition group for a feature flag.
type FeatureFlagEvaluations ¶ added in v1.12.5
type FeatureFlagEvaluations struct {
// contains filtered or unexported fields
}
FeatureFlagEvaluations is a snapshot of feature-flag evaluations for a single distinct_id, returned by Client.EvaluateFlags. It is the recommended way to evaluate many flags for a single user with a single network request: the snapshot can power any number of IsEnabled / GetFlag checks and can be attached to a Capture event via Capture.Flags so the event carries the exact values the application branched on, with no additional /flags call.
Calls to IsEnabled and GetFlag fire $feature_flag_called (deduped per (distinct_id, key, device_id)). GetFlagPayload does not fire an event.
func EvaluateFlagsWithContext ¶ added in v1.13.0
func EvaluateFlagsWithContext(ctx context.Context, client Client, payload EvaluateFlagsPayload) (*FeatureFlagEvaluations, error)
EvaluateFlagsWithContext evaluates feature flags and uses the request-scoped distinct ID attached to ctx when payload.DistinctId is empty. It does not generate personless IDs: feature flag evaluation requires a stable distinct ID and returns ErrNoDistinctID if neither payload nor ctx has one.
func (*FeatureFlagEvaluations) GetFlag ¶ added in v1.12.5
func (e *FeatureFlagEvaluations) GetFlag(key string) interface{}
GetFlag returns the value of the flag: a string for multivariate flags, true or false for boolean flags, or nil for unknown flags. The first call for a given key fires $feature_flag_called with full evaluation metadata; subsequent calls with the same response are deduped.
func (*FeatureFlagEvaluations) GetFlagPayload ¶ added in v1.12.5
func (e *FeatureFlagEvaluations) GetFlagPayload(key string) string
GetFlagPayload returns the raw JSON payload string for the flag, or "" if no payload is configured or the flag is unknown. Unlike IsEnabled and GetFlag, it does not record an access and does not fire an event.
func (*FeatureFlagEvaluations) IsEnabled ¶ added in v1.12.5
func (e *FeatureFlagEvaluations) IsEnabled(key string) bool
IsEnabled reports whether the flag is enabled for this snapshot's user. Unknown flags return false. The first call for a given key fires $feature_flag_called with full evaluation metadata; subsequent calls with the same response are deduped against the client's per-distinct_id cache.
func (*FeatureFlagEvaluations) Keys ¶ added in v1.12.5
func (e *FeatureFlagEvaluations) Keys() []string
Keys returns the sorted list of evaluated flag keys.
func (*FeatureFlagEvaluations) Only ¶ added in v1.12.5
func (e *FeatureFlagEvaluations) Only(keys []string) *FeatureFlagEvaluations
Only returns a filtered copy of this snapshot keeping only the named flags that were actually evaluated. Unknown keys are dropped with a warning.
The returned snapshot tracks access independently from the receiver.
func (*FeatureFlagEvaluations) OnlyAccessed ¶ added in v1.12.5
func (e *FeatureFlagEvaluations) OnlyAccessed() *FeatureFlagEvaluations
OnlyAccessed returns a filtered copy of this snapshot containing only the flags that were accessed via IsEnabled or GetFlag before this call.
The method honors its name: if nothing has been accessed yet, the returned snapshot is empty. Pre-access the flags you want to attach before calling.
The returned snapshot tracks access independently from the receiver; further accesses on the child do not influence what the parent sees.
type FeatureFlagPayload ¶
type FeatureFlagPayload struct {
// Key is the feature flag key to evaluate. It is required.
Key string
// DistinctId is the user distinct ID to evaluate the flag for. It is required.
DistinctId string
// DeviceId optionally provides a device_id for remote /flags requests and event deduplication.
DeviceId *string
// Groups supplies group identifiers for group-targeted flags.
Groups Groups
// PersonProperties overrides person properties used during flag evaluation.
PersonProperties Properties
// GroupProperties overrides group properties used during flag evaluation, keyed by group type.
GroupProperties map[string]Properties
// OnlyEvaluateLocally prevents fallback to remote /flags requests.
OnlyEvaluateLocally bool
// SendFeatureFlagEvents controls whether $feature_flag_called is captured.
// Nil defaults to true during validation.
SendFeatureFlagEvents *bool
}
FeatureFlagPayload configures a single legacy feature flag evaluation. It is used by Client.GetFeatureFlag, Client.IsFeatureEnabled, Client.GetFeatureFlagResult, and Client.GetFeatureFlagPayload.
type FeatureFlagPayloadNoKey ¶
type FeatureFlagPayloadNoKey struct {
// DistinctId is the user distinct ID to evaluate flags for. It is required.
DistinctId string
// DeviceId optionally provides a device_id for remote /flags requests and event deduplication.
DeviceId *string
// Groups supplies group identifiers for group-targeted flags.
Groups Groups
// PersonProperties overrides person properties used during flag evaluation.
PersonProperties Properties
// GroupProperties overrides group properties used during flag evaluation, keyed by group type.
GroupProperties map[string]Properties
// OnlyEvaluateLocally prevents fallback to remote /flags requests.
OnlyEvaluateLocally bool
// SendFeatureFlagEvents is reserved for parity with single-flag payloads.
// Nil defaults to true during validation; GetAllFlags does not currently emit per-flag access events.
SendFeatureFlagEvents *bool
}
FeatureFlagPayloadNoKey configures legacy evaluation of all flags for one user. It is used by Client.GetAllFlags.
type FeatureFlagResult ¶ added in v1.9.0
type FeatureFlagResult struct {
// Key is the feature flag key that was evaluated
Key string
// Enabled indicates whether the feature flag evaluation determined
// the flag to be in an enabled state.
Enabled bool
// RawPayload is the serialized JSON payload associated with the flag variant.
// Nil if no payload is configured.
// Use GetPayloadAs to unmarshal the payload into a specific type.
RawPayload *string
// Variant is the variant key if this is a multivariate flag.
// Nil for boolean flags.
Variant *string
// contains filtered or unexported fields
}
FeatureFlagResult represents the result of a feature flag evaluation, containing both the flag value and its payload.
func (*FeatureFlagResult) GetPayloadAs ¶ added in v1.10.0
func (r *FeatureFlagResult) GetPayloadAs(v interface{}) error
GetPayloadAs unmarshals the JSON payload into the provided type. Returns an error if the payload is empty or cannot be unmarshaled.
type FeatureFlagsPoller ¶
type FeatureFlagsPoller struct {
// Logger receives poller warnings and errors.
Logger Logger
// Endpoint is the PostHog API host used by the poller.
Endpoint string
// contains filtered or unexported fields
}
FeatureFlagsPoller periodically loads feature flag definitions for local evaluation. Applications normally interact with it through Client methods rather than constructing it directly.
func (*FeatureFlagsPoller) ForceReload ¶
func (poller *FeatureFlagsPoller) ForceReload()
ForceReload requests an immediate reload of local feature flag definitions.
func (*FeatureFlagsPoller) GetAllFlags ¶
func (poller *FeatureFlagsPoller) GetAllFlags(flagConfig FeatureFlagPayloadNoKey) (map[string]interface{}, error)
GetAllFlags evaluates every available flag for the configured user. Values are bools for boolean flags or strings for multivariate variants.
func (*FeatureFlagsPoller) GetFeatureFlag ¶
func (poller *FeatureFlagsPoller) GetFeatureFlag(flagConfig FeatureFlagPayload) (interface{}, bool, error)
GetFeatureFlag evaluates one flag using locally loaded definitions when possible. It returns the flag value, whether that value was locally evaluated, and an error. If local evaluation is inconclusive and OnlyEvaluateLocally is false, it falls back to /flags.
func (*FeatureFlagsPoller) GetFeatureFlagPayload ¶ added in v1.2.16
func (poller *FeatureFlagsPoller) GetFeatureFlagPayload(flagConfig FeatureFlagPayload) (string, error)
GetFeatureFlagPayload returns the payload for the evaluated flag value. It tries local payloads first and falls back to the remote API unless OnlyEvaluateLocally is true.
func (*FeatureFlagsPoller) GetFeatureFlagWithPayload ¶ added in v1.11.2
func (poller *FeatureFlagsPoller) GetFeatureFlagWithPayload(flagConfig FeatureFlagPayload) flagValueAndPayload
GetFeatureFlagWithPayload evaluates a feature flag once and returns both its value and payload. This avoids the double evaluation that would happen when calling GetFeatureFlag and GetFeatureFlagPayload separately.
func (*FeatureFlagsPoller) GetFeatureFlags ¶
func (poller *FeatureFlagsPoller) GetFeatureFlags() ([]FeatureFlag, error)
GetFeatureFlags returns the locally loaded feature flag definitions. It waits for the initial poll to complete and returns an error if flags were not loaded.
type FeatureFlagsResponse ¶
type FeatureFlagsResponse struct {
// Flags contains feature flag definitions for local evaluation.
Flags []FeatureFlag `json:"flags"`
// GroupTypeMapping maps group type indexes to group type names.
GroupTypeMapping *map[string]string `json:"group_type_mapping"`
// Cohorts contains cohort definitions referenced by local feature flags.
Cohorts map[string]PropertyGroup `json:"cohorts"`
}
FeatureFlagsResponse is the wire-format response from the local evaluation endpoint.
type FieldError ¶
type FieldError struct {
// The human-readable representation of the type of structure that wasn't
// initialized properly.
Type string
// The name of the field that wasn't properly initialized.
Name string
// The value of the field that wasn't properly initialized.
Value interface{}
}
FieldError describes an invalid required field in a message passed to the SDK.
func (FieldError) Error ¶
func (e FieldError) Error() string
Error returns a human-readable field validation error message.
type Filter ¶
type Filter struct {
// AggregationGroupTypeIndex identifies the group type for group-targeted flags.
AggregationGroupTypeIndex *uint8 `json:"aggregation_group_type_index"`
// Groups contains the ordered condition groups to evaluate.
Groups []FeatureFlagCondition `json:"groups"`
// Multivariate contains variant definitions for multivariate flags.
Multivariate *Variants `json:"multivariate"`
// Payloads maps flag values or variant keys to raw JSON payloads.
Payloads map[string]json.RawMessage `json:"payloads"`
// DecodedPayloads holds pre-decoded string versions of Payloads.
// Built once at flag load time to avoid per-evaluation json.Unmarshal / unquoting.
DecodedPayloads map[string]string `json:"-"`
// VariantLookupTable is pre-computed at flag load time to avoid per-evaluation
// slice allocation for multivariate flags.
VariantLookupTable []FlagVariantMeta `json:"-"`
}
Filter contains the targeting rules, variants, and payloads for a FeatureFlag.
type FlagDetail ¶ added in v1.4.6
type FlagDetail struct {
// Key is the feature flag key.
Key string `json:"key"`
// Enabled reports whether the flag is enabled for the evaluated user.
Enabled bool `json:"enabled"`
// Variant is the matched variant key for multivariate flags, or nil for boolean flags.
Variant *string `json:"variant"`
// Reason explains why the flag matched or did not match, when provided by the API.
Reason *FlagReason `json:"reason"`
// Metadata contains IDs, version, payload, and optional flag description.
Metadata FlagMetadata `json:"metadata"`
// Failed is true when the API could not evaluate this flag due to a transient failure.
Failed *bool `json:"failed,omitempty"`
}
FlagDetail represents one evaluated feature flag in the v4 /flags response format.
func NewFlagDetail ¶ added in v1.4.6
func NewFlagDetail(key string, value interface{}, payload json.RawMessage) FlagDetail
NewFlagDetail creates a FlagDetail from a flag key, a bool or string value, and an optional raw JSON payload. String values are treated as enabled variants; bool values are treated as boolean flag results.
func (FlagDetail) GetValue ¶ added in v1.4.6
func (f FlagDetail) GetValue() interface{}
GetValue returns the variant string when Variant is set; otherwise it returns Enabled.
type FlagMetadata ¶ added in v1.4.6
type FlagMetadata struct {
// ID is the numeric feature flag ID in PostHog.
ID int `json:"id"`
// Version is the feature flag version evaluated by the API.
Version int `json:"version"`
// Payload is the raw JSON payload associated with the matched flag value.
Payload json.RawMessage `json:"payload"`
// Description is the feature flag description, when returned by the API.
Description *string `json:"description,omitempty"`
}
FlagMetadata contains additional information about a flag evaluation.
type FlagProperty ¶
type FlagProperty struct {
// Key is the property key to read.
Key string `json:"key"`
// Operator is the comparison operator, such as exact, is_not, or regex.
Operator string `json:"operator"`
// Value is the comparison value for Operator.
Value interface{} `json:"value"`
// Type is the property source. Supported values include "person", "group", "cohort", and "flag".
Type string `json:"type"`
// Negation inverts the property match when true.
Negation bool `json:"negation"`
// DependencyChain tracks feature flag dependencies while evaluating nested flag properties.
DependencyChain []string `json:"dependency_chain"`
}
FlagProperty describes one property matcher in a feature flag or cohort condition.
type FlagReason ¶ added in v1.4.6
type FlagReason struct {
// Code is the machine-readable reason code returned by the API.
Code string `json:"code"`
// Description is the human-readable reason returned by the API.
Description string `json:"description"`
// ConditionIndex is the matched condition index, when available.
ConditionIndex *int `json:"condition_index"`
}
FlagReason represents why a flag was enabled or disabled.
type FlagVariant ¶
type FlagVariant struct {
// Key is the stable variant key returned by flag evaluation.
Key string `json:"key"`
// Name is the display name for the variant.
Name string `json:"name"`
// RolloutPercentage is the percentage allocated to this variant.
RolloutPercentage *float64 `json:"rollout_percentage"`
}
FlagVariant describes one multivariate feature flag variant.
type FlagVariantMeta ¶
type FlagVariantMeta struct {
// ValueMin is the inclusive lower bound of the normalized hash range.
ValueMin float64
// ValueMax is the exclusive upper bound of the normalized hash range.
ValueMax float64
// Key is the variant key for this hash range.
Key string
}
FlagVariantMeta is a precomputed hash range for a feature flag variant.
type FlagsRequestData ¶ added in v1.5.1
type FlagsRequestData struct {
// ApiKey is the PostHog project API key.
ApiKey string `json:"api_key"`
// DistinctId is the user distinct ID to evaluate flags for.
DistinctId string `json:"distinct_id"`
// DeviceId optionally identifies the device for device-aware flag evaluation.
DeviceId *string `json:"device_id,omitempty"`
// Groups contains group identifiers for group-targeted flags.
Groups Groups `json:"groups"`
// PersonProperties overrides person properties for this evaluation.
PersonProperties Properties `json:"person_properties"`
// GroupProperties overrides group properties for this evaluation, keyed by group type.
GroupProperties map[string]Properties `json:"group_properties"`
// DisableGeoIP disables GeoIP enrichment for this flags request.
DisableGeoIP bool `json:"geoip_disable,omitempty"`
// FlagKeysToEvaluate asks the server to evaluate only these flag keys when non-empty.
FlagKeysToEvaluate []string `json:"flag_keys_to_evaluate,omitempty"`
}
FlagsRequestData is the wire-format request body sent to the /flags endpoint.
type FlagsResponse ¶ added in v1.5.1
type FlagsResponse struct {
// CommonResponseFields contains response metadata shared across formats.
CommonResponseFields
// Flags contains v4-format flag details keyed by flag key.
Flags map[string]FlagDetail `json:"flags,omitempty"`
// FeatureFlags contains legacy v3 flag values keyed by flag key.
FeatureFlags map[string]interface{} `json:"featureFlags"`
// FeatureFlagPayloads contains legacy v3 raw payloads keyed by flag key.
FeatureFlagPayloads map[string]json.RawMessage `json:"featureFlagPayloads"`
}
FlagsResponse represents a normalized /flags response. It accepts both legacy v3 and current v4 response shapes.
func (*FlagsResponse) UnmarshalJSON ¶ added in v1.5.1
func (r *FlagsResponse) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom unmarshaling to handle both v3 and v4 formats
type GroupIdentify ¶
type GroupIdentify struct {
// Type is the group type, such as "company" or "organization".
Type string
// Key is the group key or ID within the group type.
Key string
// Uuid is an optional event UUID. If empty, Enqueue generates a random UUID.
Uuid string
// DistinctId is accepted for compatibility but the wire payload uses a generated group distinct ID.
DistinctId string
// Timestamp is the event timestamp. If zero, Enqueue uses the current time.
Timestamp time.Time
// Properties are sent as the $group_set properties for the group.
Properties Properties
// DisableGeoIP controls whether this group-identify event disables GeoIP lookup.
// Enqueue overwrites it from Config.GetDisableGeoIP.
DisableGeoIP bool
}
GroupIdentify represents a group analytics call that sets properties on a group. Enqueue validates Type and Key, fills Uuid, Timestamp, and DisableGeoIP, then sends the message as a $groupidentify event.
func (GroupIdentify) APIfy ¶
func (msg GroupIdentify) APIfy() APIMessage
APIfy converts a GroupIdentify message into the PostHog batch API representation.
func (GroupIdentify) Validate ¶
func (msg GroupIdentify) Validate() error
Validate checks that the group identify message has Type and Key set.
type GroupIdentifyInApi ¶
type GroupIdentifyInApi struct {
// Uuid is the event UUID sent to the batch API.
Uuid string `json:"uuid"`
// Library is the SDK name sent to the batch API.
Library string `json:"library"`
// LibraryVersion is the SDK version sent to the batch API.
LibraryVersion string `json:"library_version"`
// Timestamp is the event timestamp sent to the batch API.
Timestamp time.Time `json:"timestamp"`
// Event is always $groupidentify for GroupIdentify messages.
Event string `json:"event"`
// DistinctId is the generated group distinct ID sent to PostHog.
DistinctId string `json:"distinct_id"`
// Properties contains SDK metadata, group identifiers, and $group_set properties.
Properties Properties `json:"properties"`
}
GroupIdentifyInApi is the wire-format payload produced from a GroupIdentify message.
type Groups ¶
type Groups map[string]interface{}
Groups is used to represent groups in messages that support it. It is a free-form object so the application can set any value it sees fit but a few helper methods are defined to make it easier to instantiate groups with common fields.
type Identify ¶
type Identify struct {
// Type is reserved for SDK serialization and is overwritten by Enqueue.
Type string
// Uuid is an optional event UUID. If empty, Enqueue generates a random UUID.
Uuid string
// DistinctId is the user distinct ID whose person profile should be updated.
DistinctId string
// Timestamp is the event timestamp. If zero, Enqueue uses the current time.
Timestamp time.Time
// Properties are sent as the $set person properties for DistinctId.
Properties Properties
// DisableGeoIP controls whether this identify event disables GeoIP lookup.
// Enqueue overwrites it from Config.GetDisableGeoIP.
DisableGeoIP bool
}
Identify represents an identify call that sets person properties for a user. Enqueue validates that DistinctId is set, fills Type, Uuid, Timestamp, and DisableGeoIP, then sends the message as a $identify event.
func (Identify) APIfy ¶
func (msg Identify) APIfy() APIMessage
APIfy converts an Identify message into the PostHog batch API representation.
type IdentifyInApi ¶
type IdentifyInApi struct {
// Type is the message type sent to the batch API.
Type string `json:"type"`
// Uuid is the event UUID sent to the batch API.
Uuid string `json:"uuid"`
// Library is the SDK name sent to the batch API.
Library string `json:"library"`
// LibraryVersion is the SDK version sent to the batch API.
LibraryVersion string `json:"library_version"`
// Timestamp is the event timestamp sent to the batch API.
Timestamp time.Time `json:"timestamp"`
// Event is always $identify for Identify messages.
Event string `json:"event"`
// DistinctId is the user distinct ID sent to PostHog.
DistinctId string `json:"distinct_id"`
// Properties contains SDK metadata and system context.
Properties Properties `json:"properties"`
// Set contains the person properties to update.
Set Properties `json:"$set"`
}
IdentifyInApi is the wire-format payload produced from an Identify message.
type InAppDecider ¶ added in v1.6.7
InAppDecider reports whether a stack frame should be considered “in-app” (i.e., part of the calling application’s own code) as opposed to external dependencies, standard library, or tooling internals. The UI can use this signal to visually emphasize frames that are likely actionable.
type InconclusiveMatchError ¶
type InconclusiveMatchError struct {
// contains filtered or unexported fields
}
InconclusiveMatchError indicates that local evaluation could not conclusively match a condition.
func (*InconclusiveMatchError) Error ¶
func (e *InconclusiveMatchError) Error() string
Error returns the inconclusive match message.
type Logger ¶
type Logger interface {
// Debugf is called by PostHog client to log debug messages about the
// operations they perform. Messages logged by this method are usually
// tagged with an `DEBUG` log level in common logging libraries.
Debugf(format string, args ...interface{})
// Logf is called by PostHog client to log regular messages about the
// operations they perform. Messages logged by this method are usually
// tagged with an `INFO` log level in common logging libraries.
Logf(format string, args ...interface{})
// Warnf is called by PostHog client to log warning messages about
// the operations they perform. Messages logged by this method are usually
// tagged with an `WARN` log level in common logging libraries.
Warnf(format string, args ...interface{})
// Errorf is called by PostHog clients call this method to log errors
// they encounter while sending events to the backend servers.
// Messages logged by this method are usually tagged with an `ERROR` log
// level in common logging libraries.
Errorf(format string, args ...interface{})
}
Logger defines the logging interface used by PostHog clients.
type Message ¶
type Message interface {
// Validate checks the internal structure of the message. It returns nil when
// the message is valid or an error describing the invalid field.
Validate() error
// APIfy converts the message into its PostHog batch API representation.
APIfy() APIMessage
// contains filtered or unexported methods
}
Message represents a PostHog object that can be queued with Client.Enqueue.
Built-in message types such as Capture, Identify, Alias, GroupIdentify, and Exception implement this interface. The unexported internal method prevents external packages from defining arbitrary message implementations.
type Properties ¶
type Properties map[string]interface{}
Properties is used to represent properties in messages that support it. It is a free-form object so the application can set any value it sees fit but a few helper method are defined to make it easier to instantiate properties with common fields. Here's a quick example of how this type is meant to be used:
posthog.Capture{
DistinctId: "0123456789",
Event: "order completed",
Properties: posthog.NewProperties()
.Set("revenue", 10.0)
.Set("currency", "USD"),
}
func NewProperties ¶
func NewProperties() Properties
NewProperties creates an empty Properties map for fluent construction.
func SlogAttrsAsProperties ¶ added in v1.12.0
func SlogAttrsAsProperties(_ context.Context, r slog.Record) Properties
SlogAttrsAsProperties is a convenience implementation of the fn passed to WithPropertiesFn. It copies every slog.Record attribute into a Properties map, so log fields flow onto the captured exception event verbatim.
Usage: posthog.WithPropertiesFn(posthog.SlogAttrsAsProperties)
Note: this ships all attrs to PostHog — make sure none contain sensitive data, or write a filtering fn instead.
func (Properties) Merge ¶ added in v1.2.15
func (p Properties) Merge(props Properties) Properties
Merge adds the properties from the provided `props` into the receiver `p`. If a property in `props` already exists in `p`, its value will be overwritten.
func (Properties) Set ¶
func (p Properties) Set(name string, value interface{}) Properties
Set assigns a property value and returns the receiver.
type PropertyGroup ¶
type PropertyGroup struct {
// Type is the boolean operator joining Values, such as AND or OR.
Type string `json:"type"`
// Values contains nested PropertyGroup values or FlagProperty values.
Values []any `json:"values"`
// ParsedValues holds pre-parsed typed values from Values.
// Built once at flag load time to avoid reconstructing FlagProperty/PropertyGroup
// from map[string]any on every cohort evaluation.
ParsedValues []parsedPropertyValue `json:"-"`
}
PropertyGroup describes a nested property group used by cohorts and flag conditions.
type RequestContext ¶ added in v1.13.0
type RequestContext struct {
// DistinctId is the request-scoped user distinct ID.
DistinctId string
// SessionId is the request-scoped PostHog session ID.
SessionId string
// Properties are request-scoped properties merged into capture and exception events.
Properties Properties
}
RequestContext carries request-scoped PostHog metadata that is applied to capture and exception events enqueued with EnqueueWithContext.
DistinctId and SessionId usually come from PostHog tracing headers. Properties usually contain safe request metadata such as $current_url, $request_method, $request_path, $user_agent, and $ip.
func ExtractRequestContext ¶ added in v1.13.0
func ExtractRequestContext(r *http.Request, captureTracingHeaders bool) RequestContext
ExtractRequestContext extracts sanitized PostHog request context from an HTTP request. Request metadata is always extracted. Tracing headers are only read when captureTracingHeaders is true.
func RequestContextFromContext ¶ added in v1.13.0
func RequestContextFromContext(ctx context.Context) (RequestContext, bool)
RequestContextFromContext returns the PostHog request metadata attached to ctx, if any.
type RequestContextOption ¶ added in v1.13.0
type RequestContextOption func(*RequestContextOptions)
RequestContextOption customizes request context middleware.
func WithCapturePanics ¶ added in v1.13.0
func WithCapturePanics(client EnqueueClient) RequestContextOption
WithCapturePanics configures request context middleware to capture downstream panics as PostHog exception events using client, then re-panic with the original value.
func WithCaptureTracingHeaders ¶ added in v1.13.0
func WithCaptureTracingHeaders(enabled bool) RequestContextOption
WithCaptureTracingHeaders configures whether request context middleware reads PostHog tracing headers.
type RequestContextOptions ¶ added in v1.13.0
type RequestContextOptions struct {
// CaptureTracingHeaders controls whether X-PostHog-Distinct-Id and X-PostHog-Session-Id
// are read into request-scoped analytics context. It defaults to true in NewRequestContextMiddleware.
// When disabled, the middleware still attaches request metadata to the request context.
CaptureTracingHeaders bool
// CapturePanics controls whether NewRequestContextMiddleware captures downstream panics as
// PostHog exception events before re-panicking. It defaults to false.
CapturePanics bool
// PanicCaptureClient receives panic exception events when CapturePanics is enabled.
PanicCaptureClient EnqueueClient
}
RequestContextOptions configures NewRequestContextMiddleware.
type RequiresServerEvaluationError ¶ added in v1.6.12
type RequiresServerEvaluationError struct {
// contains filtered or unexported fields
}
RequiresServerEvaluationError is returned when feature flag evaluation requires server-side data that is not available locally (e.g., static cohorts, experience continuity). This error should propagate immediately to trigger API fallback, unlike InconclusiveMatchError which allows trying other conditions.
func (*RequiresServerEvaluationError) Error ¶ added in v1.6.12
func (e *RequiresServerEvaluationError) Error() string
Error returns the reason server-side evaluation is required.
type SendFeatureFlagsBool ¶ added in v1.6.1
type SendFeatureFlagsBool bool
SendFeatureFlagsBool wraps a boolean value to implement SendFeatureFlagsValue.
func (SendFeatureFlagsBool) GetOptions ¶ added in v1.6.1
func (b SendFeatureFlagsBool) GetOptions() *SendFeatureFlagsOptions
GetOptions returns nil because SendFeatureFlagsBool has no additional options.
func (SendFeatureFlagsBool) ShouldSend ¶ added in v1.6.1
func (b SendFeatureFlagsBool) ShouldSend() bool
ShouldSend reports the wrapped boolean value.
type SendFeatureFlagsOptions ¶ added in v1.6.1
type SendFeatureFlagsOptions struct {
// OnlyEvaluateLocally forces evaluation to use locally loaded flag definitions only.
OnlyEvaluateLocally bool
// DeviceId provides a device_id for remote flag evaluation requests.
DeviceId *string
// PersonProperties provides explicit person properties for flag evaluation.
PersonProperties Properties
// GroupProperties provides explicit group properties for flag evaluation.
GroupProperties map[string]Properties
}
SendFeatureFlagsOptions allows granular control over legacy feature flag evaluation for Capture. Deprecated: Prefer Client.EvaluateFlags and Capture.Flags so captures use the exact flag snapshot your application branched on without another /flags request.
func (*SendFeatureFlagsOptions) GetOptions ¶ added in v1.6.1
func (opts *SendFeatureFlagsOptions) GetOptions() *SendFeatureFlagsOptions
GetOptions returns opts so Capture can pass the options to feature flag evaluation.
func (*SendFeatureFlagsOptions) ShouldSend ¶ added in v1.6.1
func (opts *SendFeatureFlagsOptions) ShouldSend() bool
ShouldSend reports true when opts is non-nil.
type SendFeatureFlagsValue ¶ added in v1.6.1
type SendFeatureFlagsValue interface {
// ShouldSend reports whether Enqueue should attach feature flag values to the Capture event.
ShouldSend() bool
// GetOptions returns optional feature flag evaluation parameters, or nil for boolean-only values.
GetOptions() *SendFeatureFlagsOptions
}
SendFeatureFlagsValue defines the legacy Capture.SendFeatureFlags configuration interface.
func SendFeatureFlags ¶ added in v1.6.1
func SendFeatureFlags(enabled bool) SendFeatureFlagsValue
SendFeatureFlags converts enabled into a legacy Capture.SendFeatureFlags value. Deprecated: Prefer Client.EvaluateFlags and Capture.Flags.
func SendFeatureFlagsWithOptions ¶ added in v1.6.1
func SendFeatureFlagsWithOptions(opts *SendFeatureFlagsOptions) SendFeatureFlagsValue
SendFeatureFlagsWithOptions wraps legacy feature flag capture options. Deprecated: Prefer Client.EvaluateFlags and Capture.Flags.
type SlogCaptureHandler ¶ added in v1.6.7
type SlogCaptureHandler struct {
// contains filtered or unexported fields
}
SlogCaptureHandler wraps a slog.Handler and mirrors qualifying records to PostHog error tracking using client.Enqueue(Exception{...}).
func NewSlogCaptureHandler ¶ added in v1.6.7
func NewSlogCaptureHandler(next slog.Handler, client EnqueueClient, opts ...SlogOption) *SlogCaptureHandler
NewSlogCaptureHandler wraps next and mirrors qualifying slog records to PostHog.
The next parameter receives all records as your normal handler. The client parameter receives captured Exception messages. The opts parameters customize capture level, distinct ID resolution, stack traces, descriptions, fingerprints, and extra properties.
You typically wrap your existing handler:
client, err := posthog.NewWithConfig(...)
// error handling and `defer client.Close()` call
base := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})
logger := slog.New(posthog.NewSlogCaptureHandler(base, client,
posthog.WithDistinctIDFn(func(ctx context.Context, r slog.Record) string {
return "my-user-id" // or pull from ctx
}),
))
func (*SlogCaptureHandler) Enabled ¶ added in v1.6.7
Enabled reports whether either the wrapped handler or PostHog capture wants records at level.
func (*SlogCaptureHandler) Handle ¶ added in v1.6.7
Handle forwards the record to the wrapped handler and captures qualifying records as exceptions. Enqueue errors are ignored so logging remains non-intrusive.
type SlogOption ¶ added in v1.6.7
type SlogOption func(*captureConfig)
SlogOption customizes NewSlogCaptureHandler.
func WithDescriptionExtractor ¶ added in v1.6.7
func WithDescriptionExtractor(extractor DescriptionExtractor) SlogOption
WithDescriptionExtractor sets the DescriptionExtractor used for captured exceptions. The extractor parameter must be non-nil.
func WithDistinctIDFn ¶ added in v1.6.7
WithDistinctIDFn sets the function used to resolve the exception DistinctId. The fn parameter must be non-nil. If fn returns an empty string, the slog record is not captured.
func WithFingerprintFn ¶ added in v1.6.7
WithFingerprintFn sets the function used to compute an optional exception fingerprint. The fn parameter must be non-nil.
func WithMinCaptureLevel ¶ added in v1.6.7
func WithMinCaptureLevel(l slog.Level) SlogOption
WithMinCaptureLevel sets the minimum slog level captured as a PostHog exception. Records below this level are still passed to the wrapped handler.
func WithPropertiesFn ¶ added in v1.12.0
func WithPropertiesFn(fn func(ctx context.Context, r slog.Record) Properties) SlogOption
WithPropertiesFn sets a function that returns custom properties for captured exceptions. Built-in exception properties take precedence if keys collide.
func WithSkip ¶ added in v1.6.7
func WithSkip(n int) SlogOption
WithSkip sets how many stack frames the stack trace extractor should skip. Values less than or equal to zero are ignored.
func WithStackTraceExtractor ¶ added in v1.6.7
func WithStackTraceExtractor(extractor StackTraceExtractor) SlogOption
WithStackTraceExtractor sets the StackTraceExtractor used for captured exceptions. The extractor parameter must be non-nil.
type StackFrame ¶ added in v1.6.7
type StackFrame struct {
// Filename is the source file path for the frame.
Filename string `json:"filename"`
// LineNo is the one-based source line number.
LineNo int `json:"lineno"`
// Function is the fully qualified function name.
Function string `json:"function"`
// InApp reports whether the frame is considered application code.
InApp bool `json:"in_app"`
// Synthetic reports whether the frame was synthesized by instrumentation.
Synthetic bool `json:"synthetic"`
// Platform identifies the runtime platform; Go frames use "go".
Platform string `json:"platform"`
}
StackFrame represents a single "Frame" within a stack trace. Documentation about the available fields can be found here: https://github.com/PostHog/posthog/blob/39b9326320c23acbdc6e96a8beb41b30d3c99099/rust/cymbal/src/langs/go.rs#L7
type StackTraceExtractor ¶ added in v1.6.7
type StackTraceExtractor interface {
// GetStackTrace returns a PostHog-compatible stack trace.
//
// The skip parameter controls how many leading frames to omit before
// recording. Use it to drop extractor/logging internals and start at the
// application call site. For example, a skip of 3–5 is typically enough to
// hide wrapper layers when called from a slog handler.
GetStackTrace(skip int) *ExceptionStacktrace
}
StackTraceExtractor produces a stack trace for the current goroutine to enrich captured exceptions with call-site context.
type Ticker ¶
type Ticker struct {
// C receives the time for each backoff tick and is closed after Stop.
C <-chan time.Time
// contains filtered or unexported fields
}
Ticker delivers ticks using successive durations from a Backoff.
type Variants ¶
type Variants struct {
// Variants is the ordered list of possible flag variants.
Variants []FlagVariant `json:"variants"`
}
Variants contains all variants configured for a multivariate feature flag.
Source Files
¶
- alias.go
- backoff.go
- capture.go
- config.go
- error.go
- error_tracking.go
- error_tracking_slog.go
- error_tracking_slog_options.go
- error_tracking_stack_trace.go
- feature_flag_config.go
- feature_flag_errors.go
- feature_flag_evaluations.go
- featureflags.go
- flags.go
- group_identify.go
- groups.go
- identify.go
- logger.go
- message.go
- noop_posthog.go
- os_info_linux.go
- posthog.go
- properties.go
- request_context.go
- system_context.go
- timeout_16.go
- version.go