PostHog Go SDK
Getting started
The Go SDK runs on your server, on Go 1.21 or later.
To send your first event, create a client with your project token and host from your project settings, then call Enqueue with a Capture.
The client queues events and sends them in batches, so call Close before your program exits, or the last events are lost.
Install the module (Go 1.21 or later):
Create a client with your project API key, send an event, and close the client to flush the queue:
Setup
Config
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.
Config.GetDisableGeoIP
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.
Config.GetIsServer
GetIsServer reports whether events should include the $is_server property. It is on by default because posthog-go is mainly used server-side; set Config.IsServer to Ptr(false) for CLI/client usage to omit $is_server.
Config.Validate
Validate verifies that fields that don't have zero-values are set to valid values, returns an error describing the problem if a field was invalid.
posthog.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.
posthog.NewWithConfig
NewWithConfig creates a Client with the provided PostHog project API key and Config.
The apiKey, Config.Endpoint, Config.SecretKey, 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.
Capture
Capture
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.
Capture.APIfy
APIfy converts a Capture message into the PostHog batch API representation.
Capture.Validate
Validate checks that the capture message has a non-empty Event and DistinctId.
EnqueueClient.Enqueue
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:
Enqueue returns an error if the message could not be queued, which happens when the client is closed, the message is invalid, or the in-memory queue is full (ErrQueueFull) -- in the latter case the message is dropped rather than blocking the caller. A full-queue drop is reported only through this returned error, not through Callback.Failure.
Bulk or backfill workloads that can enqueue faster than the client uploads should check the returned error for ErrQueueFull and throttle or retry (or raise Config.MaxQueueSize); otherwise events are dropped, not delayed.
posthog.EnqueueWithContext
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.
Identify
Identify
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.
Identify.APIfy
APIfy converts an Identify message into the PostHog batch API representation.
Identify.Validate
Validate checks that the identify message has a DistinctId.
Alias
Alias
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.
Alias.APIfy
APIfy converts an Alias message into the PostHog batch API representation.
Alias.Validate
Validate checks that the alias message has both DistinctId and Alias set.
Capture exception
Exception
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.
Exception.APIfy
APIfy converts an Exception message into the PostHog batch API representation.
Exception.Validate
Validate checks that the exception has a DistinctId and at least one valid ExceptionItem.
posthog.NewDefaultException
NewDefaultException builds an Exception with a default stack trace.
The timestamp parameter becomes Exception.Timestamp; UTC is preferred, and Enqueue converts non-UTC values to the equivalent UTC instant. 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.
posthog.NewSlogCaptureHandler
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:
Emails
Client.Emails
Emails sends transactional email from PostHog email templates or from content your code rendered, and reads the status of each email it sent. It needs Config.SecretKey, a project secret API key with the transactional_email:write scope. Close waits for email requests in flight, and a request after Close fails with the code client_closed.
Flush
Client.Flush
Flush sends queued messages and waits for the current delivery cycle without closing the client. Retryable failures end the cycle while the transport retains the events for its scheduled retry. Flush does not bypass retry backoff. Delivery failures use the existing retry policy and Callback.Failure; a nil result does not guarantee successful ingestion. Use FlushWithContext to bound the wait. Do not call a blocking Flush from a delivery callback, which is itself part of the delivery cycle.
Client.FlushWithContext
FlushWithContext is Flush with a caller-controlled deadline. Cancellation stops only this caller's wait, not delivery or future use of the client. Messages accepted before the call are covered; concurrent Enqueue calls may be included in this cycle or a later one. Calls after Close return ErrClosed.
Get feature flag
Client.GetFeatureFlag
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.
Get feature flag payload
Client.GetFeatureFlagPayload
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.
Get feature flag result
Client.GetFeatureFlagResult
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 ErrNoSecretKey when OnlyEvaluateLocally is true without SecretKey or a FlagDefinitionCacheProvider.
Get feature flags
Client.GetAllFlags
GetAllFlags evaluates all flags for a user. Returned values are booleans for boolean flags and strings for multivariate variants. It returns ErrNoSecretKey when OnlyEvaluateLocally is true without SecretKey or a FlagDefinitionCacheProvider.
Evaluate flags
Client.EvaluateFlags
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 FlagKeys contains a key missing from loaded local definitions, EvaluateFlags includes it in the remote /flags fallback unless OnlyEvaluateLocally is true. If the remote 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 neither SecretKey nor a FlagDefinitionCacheProvider is configured, returns ErrNoSecretKey.
EvaluateFlagsPayload
EvaluateFlagsPayload is the input to Client.EvaluateFlags.
posthog.EvaluateFlagsWithContext
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.
Group identify
GroupIdentify
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.
GroupIdentify.APIfy
APIfy converts a GroupIdentify message into the PostHog batch API representation.
GroupIdentify.Validate
Validate checks that the group identify message has Type and Key set.
Is feature enabled
Client.IsFeatureEnabled
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.
Reload feature flags
Client.ReloadFeatureFlags
ReloadFeatureFlags forces a reload of feature flags. If neither SecretKey nor a FlagDefinitionCacheProvider is configured, returns ErrNoSecretKey.
Shutdown
Client.Close
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.
Client.CloseWithContext
CloseWithContext gracefully shuts down the client with the provided context. The context can be used to control the shutdown deadline.
Before send hook
BeforeSendFunc
BeforeSendFunc is called before a message is converted to the PostHog API format. It can return a modified message, or nil to drop the message. If the hook panics, returns an invalid message, or returns a different message type, the message is dropped.
The SDK passes an isolated copy of SDK-owned mutable fields where practical: Properties and Groups clone common JSON-like maps and slices, and Exception clones its exception list, stack traces, mechanisms, fingerprint, and debug images. Arbitrary reference values stored inside Properties or Groups (for example, pointers or custom mutable structs held as interface{} values) are not deep-cloned and can still share state with the caller.
SDK utils
Client.GetRemoteConfigPayload
GetRemoteConfigPayload returns the decrypted payload for a remote config flag key. It requires Config.SecretKey and returns ErrNoSecretKey when missing.
posthog.NewRequestContextMiddleware
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.
posthog.Ptr
Ptr returns a pointer to v.
posthog.SimpleInAppDecider
SimpleInAppDecider is a basic InAppDecider that classifies frames by file path. It excludes vendored modules, module cache paths, and Go toolchain paths.
posthog.WithFreshRequestContext
WithFreshRequestContext returns a child context with PostHog request metadata attached without inheriting any existing PostHog request context from the parent.
posthog.WithRequestContext
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.
Constants
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.
Version of the client.
Variables
ErrFlagNotFound is returned when a feature flag does not exist or is disabled. Use errors.Is(err, ErrFlagNotFound) to check for this error.
FeatureFlagEvaluations
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.
FeatureFlagEvaluations.GetFlag
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.
FeatureFlagEvaluations.GetFlagPayload
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.
FeatureFlagEvaluations.IsEnabled
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.
FeatureFlagEvaluations.Keys
Keys returns the sorted list of evaluated flag keys.
FeatureFlagEvaluations.Only
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.
FeatureFlagEvaluations.OnlyAccessed
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.
FeatureFlagEvaluations.UnresolvedFlags
UnresolvedFlags returns the flags that have a loaded local definition but that neither local evaluation nor a remote fallback resolved, mapped to the reason local evaluation was inconclusive. These flags are absent from Keys, IsEnabled returns false and GetFlag returns nil for them. Reading this does not record an access and does not fire an event. The returned map is a copy.
Snapshots returned by Only and OnlyAccessed have no unresolved flags.
Types
APIError
APIError represents an HTTP API error with a status code. This allows classifyError to generate api_error_{status} strings.
APIError.Error
Error returns the API error message.
posthog.NewAPIError
NewAPIError creates an APIError with the given HTTP status code and message.
APIMessage
APIMessage is a wire-format message produced by Message.APIfy and passed to callbacks. Legacy API message structs may still expose top-level fields such as type, library, library_version, and send_feature_flags for compatibility. Capture ingestion uses event plus properties such as $lib, $lib_version, $feature/<key>, and $active_feature_flags instead.
AliasInApi
AliasInApi is the wire-format payload produced from an Alias message.
AliasInApiProperties
AliasInApiProperties is the wire-format properties object for an Alias message.
AliasInApiProperties.ToProperties
Backoff
Backoff calculates exponential retry delays with optional jitter and a maximum cap.
Backoff.Duration
Duration returns the backoff interval for the given attempt.
Backoff.NewTicker
NewTicker starts a ticker that waits Duration(0), Duration(1), and so on between ticks.
Backoff.Sleep
Sleep pauses the current goroutine for the backoff interval for the given attempt.
posthog.DefaultBackoff
DefaultBackoff creates a Backoff with the SDK's default retry policy:
posthog.NewBackoff
NewBackoff creates a Backoff with the provided base duration, exponential factor, jitter ratio, and maximum cap duration.
Callback
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.
CaptureEventError
CaptureEventError is delivered to Callback.Failure for a single event that the capture-v1 endpoint rejected: either a terminal "drop" result, or an event still asking to "retry" once the attempt budget is exhausted. Callers can use errors.As to inspect the per-event outcome.
This error type is produced exclusively on the 200-with-partial-results path — when the batch-level HTTP exchange succeeds but individual events within the batch are rejected or not persisted. It is never returned for batch-level transport failures (use CaptureRequestError for those via errors.As).
CaptureEventError.Error
CaptureInApi
CaptureInApi is the wire-format payload produced from a Capture message.
CaptureMode
CaptureMode selects the capture wire protocol used for event ingestion.
CaptureRequestError
CaptureRequestError is delivered to Callback.Failure when an entire capture-v1 request fails: a non-2xx status, a transport error, or a malformed 2xx body. It carries the HTTP status and any structured error body the endpoint returned, and unwraps to the underlying transport/parse error when there is one.
This error type covers batch-level failures — transport errors, terminal HTTP statuses (400/401/429/...), retryable statuses (5xx) whose retry budget is exhausted, and 2xx responses with unparseable bodies. For per-event failures within a successful batch response, see CaptureEventError.
CaptureRequestError.Error
CaptureRequestError.Unwrap
CodeEmail
CodeEmail sends content your code rendered, named by a key. PostHog sends the subject and bodies as is and never stores them; it keeps attachments, as Attachments says. To send a React email, render it to HTML in your app and pass the HTML.
CommonResponseFields
CommonResponseFields contains fields common to all flags response versions.
CompressionMode
CompressionMode specifies the compression algorithm for batch payloads.
CompressionMode.String
String returns a human-readable codec name, used in config validation errors and debug logs. It is not the on-the-wire Content-Encoding token (brotli's token is "br"); see compressV1Body for wire tokens.
ConfigError
ConfigError is returned by NewWithConfig when a Config field has an invalid value.
ConfigError.Error
Error returns a human-readable configuration error message.
DebugImage
DebugImage describes a binary image loaded into the process, sent as the event-level $debug_images property so PostHog can symbolicate raw frame addresses against debug symbols uploaded with posthog-cli symbol-sets upload.
DebugImageProvider
DebugImageProvider is implemented by stack trace extractors that can also report the binary images their frames reference. Integrations that accept a StackTraceExtractor (e.g. the slog capture handler) use it to attach $debug_images to the exceptions they build.
DecideRequestData
DecideRequestData is the legacy wire-format request body for flag decide calls.
DecideResponse
DecideResponse is the legacy wire-format response body for flag decide calls.
DefaultStackTraceExtractor
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.
DefaultStackTraceExtractor.GetDebugImages
GetDebugImages returns the debug images referenced by captured frames — currently the main executable, when its identity could be determined.
DefaultStackTraceExtractor.GetStackTrace
GetStackTrace captures the current goroutine stack in wire order (outermost frame first, capture site last). The skip parameter omits leading runtime.Callers frames before conversion.
When the running executable's identity is known (see DebugImage), frames are emitted as client-expanded inline groups for server-side symbolication: each physical stack frame and the entries the runtime synthesizes for calls inlined into it share one raw return address, with the synthesized layers tagged inline. PostHog resolves that address once against uploaded debug symbols and atomically replaces the whole group with its own expansion (exact inline chain, source context), or keeps these runtime-resolved frames verbatim when no symbols are uploaded. When the executable can't be identified, frames keep the plain pre-existing shape.
DescriptionExtractor
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.
Email
Email is the content of one send: a TemplateEmail or a CodeEmail.
EmailAttachment
EmailAttachment is a file sent with a CodeEmail.
EmailError
EmailError reports that PostHog did not queue the email or return its status, or that the client could not tell whether it did. Every error that Emails returns is an *EmailError; read it with errors.As.
Branch on Code, PostHog's stable error code such as "recipient_suppressed", or an SDK code such as "network_error" or "missing_app_host". Name is its coarse category. The error never holds the secret key or the request body.
EmailError.Error
EmailError.Unwrap
Unwrap returns the cause, such as a network error, context.DeadlineExceeded, ErrSDKDisabled or ErrClosed.
EmailErrorName
EmailErrorName is a coarse category of an EmailError, for code that branches on the kind of failure rather than the exact code. The names follow Resend's error names, so code moved from Resend keeps working.
EmailStatus
EmailStatus is what happened to an email that Emails.Send queued.
EmailTracking
EmailTracking says what PostHog tracks for a CodeEmail. Make one with EmailTrackingOn, EmailTrackingOff or EmailTrackingWith.
EmailTracking.MarshalJSON
MarshalJSON encodes the tracking as true, false or an object of the kinds that are set.
posthog.EmailTrackingOff
EmailTrackingOff turns off every kind of tracking, including kinds PostHog adds later. PostHog then can't count the email's opens and clicks, and captures no engagement events.
posthog.EmailTrackingOn
EmailTrackingOn tracks opens and clicks and captures engagement events. Use it only when the email's links are safe to send through a redirect.
posthog.EmailTrackingWith
EmailTrackingWith sets each kind of tracking on its own.
EmailTrackingOptions
EmailTrackingOptions turns each kind of tracking on or off. A nil field keeps its default.
EmailWarning
EmailWarning is a warning PostHog returned with a queued email.
Emails
Emails sends transactional email, such as a password reset or a receipt, to one recipient per call, and reads the status of an email it sent.
It needs Config.SecretKey, a project secret API key (phs_...) with the transactional_email:write scope, the "Send transactional email" preset in your project settings. A key with only transactional_email:read can read statuses but not send. Keys made with hog_flow:write still work. Requests go to Config.AppHost, or to the PostHog Cloud app host of Config.Endpoint.
Every error is an *EmailError. Network errors, rate limits, an idempotency key in flight and an unavailable service are retried up to Config.EmailRequestMaxRetries times, with the same idempotency key.
EnqueueClient
EnqueueClient is the minimal interface implemented by clients that can queue PostHog messages.
ErrorExtractor
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.
ErrorExtractor.ExtractDescription
ExtractDescription returns the first matching error string from the slog record or Fallback.
ExceptionInApi
ExceptionInApi is the wire-format payload produced from an Exception message.
ExceptionInApiProperties
ExceptionInApiProperties is the wire-format properties object for an Exception message.
ExceptionInApiProperties.MarshalJSON
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.
ExceptionInApiProperties.ToProperties
ExceptionItem
ExceptionItem describes one exception in an Exception event.
ExceptionItem.Validate
Validate checks that the exception item has Type and Value set.
ExceptionMechanism
ExceptionMechanism describes whether an exception was handled or synthesized.
ExceptionStacktrace
ExceptionStacktrace is a PostHog-compatible stack trace.
FeatureFlag
FeatureFlag is a feature flag definition returned by the local evaluation endpoint.
FeatureFlagCondition
FeatureFlagCondition describes one condition group for a feature flag.
FeatureFlagPayload
FeatureFlagPayload configures a single legacy feature flag evaluation. It is used by Client.GetFeatureFlag, Client.IsFeatureEnabled, Client.GetFeatureFlagResult, and Client.GetFeatureFlagPayload.
FeatureFlagPayloadNoKey
FeatureFlagPayloadNoKey configures legacy evaluation of all flags for one user. It is used by Client.GetAllFlags.
FeatureFlagResult
FeatureFlagResult represents the result of a feature flag evaluation, containing both the flag value and its payload.
FeatureFlagResult.GetPayloadAs
GetPayloadAs unmarshals the JSON payload into the provided type. Returns an error if the payload is empty or cannot be unmarshaled.
FeatureFlagsPoller
FeatureFlagsPoller periodically loads feature flag definitions for local evaluation. Applications normally interact with it through Client methods rather than constructing it directly.
FeatureFlagsPoller.ForceReload
ForceReload requests an immediate reload of local feature flag definitions. It does nothing once the poller has shut down. The send selects on shutdown so a reload racing Close cannot send on a closed channel.
FeatureFlagsPoller.GetAllFlags
GetAllFlags evaluates every available flag for the configured user. Values are bools for boolean flags or strings for multivariate variants.
FeatureFlagsPoller.GetFeatureFlag
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.
FeatureFlagsPoller.GetFeatureFlagPayload
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.
FeatureFlagsPoller.GetFeatureFlagWithPayload
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.
FeatureFlagsPoller.GetFeatureFlags
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.
FeatureFlagsResponse
FeatureFlagsResponse is the wire-format response from the local evaluation endpoint.
FieldError
FieldError describes an invalid required field in a message passed to the SDK.
FieldError.Error
Error returns a human-readable field validation error message.
Filter
Filter contains the targeting rules, variants, and payloads for a FeatureFlag.
FlagDefinitionCacheProvider
FlagDefinitionCacheProvider shares feature flag definitions between SDK instances through an external cache such as Redis. Definition data is opaque: providers store and return it unchanged; the SDK validates and interprets it. Without a SecretKey, SDK instances only read the cache and never consult the fetch decision or publish definitions. Instances with a SecretKey consult the fetch decision and publish definitions after an elected fetch. Implementations should honor context cancellation so polling and resource cleanup can finish promptly.
EXPERIMENTAL: this interface may change in a minor version bump.
FlagDetail
FlagDetail represents one evaluated feature flag in the v4 /flags response format.
FlagDetail.GetValue
GetValue returns the variant string when Variant is set; otherwise it returns Enabled.
posthog.NewFlagDetail
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.
FlagMetadata
FlagMetadata contains additional information about a flag evaluation.
FlagProperty
FlagProperty describes one property matcher in a feature flag or cohort condition.
FlagReason
FlagReason represents why a flag was enabled or disabled.
FlagVariant
FlagVariant describes one multivariate feature flag variant.
FlagVariantMeta
FlagVariantMeta is a precomputed hash range for a feature flag variant.
FlagsRequestData
FlagsRequestData is the wire-format request body sent to the /flags endpoint.
FlagsResponse
FlagsResponse represents a normalized /flags response. It accepts both legacy v3 and current v4 response shapes.
FlagsResponse.UnmarshalJSON
UnmarshalJSON implements custom unmarshaling to handle both v3 and v4 formats
GroupIdentifyInApi
GroupIdentifyInApi is the wire-format payload produced from a GroupIdentify message.
Groups
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.
Groups.Set
Set assigns a group type to a group key or ID and returns the receiver.
posthog.NewGroups
NewGroups creates an empty Groups map for fluent construction.
Holdout
Holdout is the experiment holdout configuration attached to a feature flag. Identifiers inside the holdout are excluded from the flag's release conditions and resolve to the synthetic variant "holdout-<id>".
IdentifyInApi
IdentifyInApi is the wire-format payload produced from an Identify message.
InAppDecider
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.
InconclusiveMatchError
InconclusiveMatchError indicates that local evaluation could not conclusively match a condition.
InconclusiveMatchError.Error
Error returns the inconclusive match message.
Logger
Logger defines the logging interface used by PostHog clients.
posthog.StdLogger
StdLogger wraps a standard log.Logger as a PostHog Logger. The verbose parameter controls whether Debugf messages are emitted.
Message
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.
Properties
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:
Properties.Merge
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.
Properties.Set
Set assigns a property value and returns the receiver.
posthog.NewProperties
NewProperties creates an empty Properties map for fluent construction.
posthog.SlogAttrsAsProperties
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.
PropertyGroup
PropertyGroup describes a nested property group used by cohorts and flag conditions.
RequestContext
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.
posthog.ExtractRequestContext
ExtractRequestContext extracts sanitized PostHog request context from an HTTP request. Request metadata is always extracted. Tracing headers are only read when captureTracingHeaders is true.
posthog.RequestContextFromContext
RequestContextFromContext returns the PostHog request metadata attached to ctx, if any.
RequestContextOption
RequestContextOption customizes request context middleware.
posthog.WithCapturePanics
WithCapturePanics configures request context middleware to capture downstream panics as PostHog exception events using client, then re-panic with the original value.
posthog.WithCaptureTracingHeaders
WithCaptureTracingHeaders configures whether request context middleware reads PostHog tracing headers.
RequestContextOptions
RequestContextOptions configures NewRequestContextMiddleware.
RequiresServerEvaluationError
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.
RequiresServerEvaluationError.Error
Error returns the reason server-side evaluation is required.
SendEmailResult
SendEmailResult is an email that PostHog queued.
SendFeatureFlagsBool
SendFeatureFlagsBool wraps a boolean value to implement SendFeatureFlagsValue.
SendFeatureFlagsBool.GetOptions
GetOptions returns nil because SendFeatureFlagsBool has no additional options.
SendFeatureFlagsBool.ShouldSend
ShouldSend reports the wrapped boolean value.
SendFeatureFlagsOptions
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.
SendFeatureFlagsOptions.GetOptions
GetOptions returns opts so Capture can pass the options to feature flag evaluation.
SendFeatureFlagsOptions.ShouldSend
ShouldSend reports true when opts is non-nil.
SendFeatureFlagsValue
SendFeatureFlagsValue defines the legacy Capture.SendFeatureFlags configuration interface.
posthog.SendFeatureFlags
SendFeatureFlags converts enabled into a legacy Capture.SendFeatureFlags value. Deprecated: Prefer Client.EvaluateFlags and Capture.Flags.
posthog.SendFeatureFlagsWithOptions
SendFeatureFlagsWithOptions wraps legacy feature flag capture options. Deprecated: Prefer Client.EvaluateFlags and Capture.Flags.
SlogCaptureHandler
SlogCaptureHandler wraps a slog.Handler and mirrors qualifying records to PostHog error tracking using client.Enqueue(Exception{...}).
SlogCaptureHandler.Enabled
Enabled reports whether either the wrapped handler or PostHog capture wants records at level.
SlogCaptureHandler.Handle
Handle forwards the record to the wrapped handler and captures qualifying records as exceptions. Enqueue errors are ignored so logging remains non-intrusive.
SlogCaptureHandler.WithAttrs
WithAttrs returns a handler with attrs applied to the wrapped handler.
SlogCaptureHandler.WithGroup
WithGroup returns a handler with name applied to the wrapped handler's group.
SlogOption
SlogOption customizes NewSlogCaptureHandler.
posthog.WithDescriptionExtractor
WithDescriptionExtractor sets the DescriptionExtractor used for captured exceptions. The extractor parameter must be non-nil.
posthog.WithDistinctIDFn
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.
posthog.WithFingerprintFn
WithFingerprintFn sets the function used to compute an optional exception fingerprint. The fn parameter must be non-nil.
posthog.WithMinCaptureLevel
WithMinCaptureLevel sets the minimum slog level captured as a PostHog exception. Records below this level are still passed to the wrapped handler.
posthog.WithPropertiesFn
WithPropertiesFn sets a function that returns custom properties for captured exceptions. Built-in exception properties take precedence if keys collide.
posthog.WithSkip
WithSkip sets how many stack frames the stack trace extractor should skip. Values less than or equal to zero are ignored.
posthog.WithStackTraceExtractor
WithStackTraceExtractor sets the StackTraceExtractor used for captured exceptions. The extractor parameter must be non-nil.
StackFrame
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
StackTraceExtractor
StackTraceExtractor produces a stack trace for the current goroutine to enrich captured exceptions with call-site context.
TemplateEmail
TemplateEmail sends an email template made transactional in PostHog, by its ID. The template sets its own sender, subject and content, and follows the project's engagement setting.
Ticker
Ticker delivers ticks using successive durations from a Backoff.
Ticker.Stop
Stop stops the ticker goroutine and closes C. Stop should be called at most once.
UnresolvedFlagReason
UnresolvedFlagReason explains why local evaluation could not resolve a flag. Experience continuity and unsupported definitions come from the flag's definition, missing context from the evaluation call, and unresolved dependencies from a flag the definition depends on.
Variants
Variants contains all variants configured for a multivariate feature flag.





