posthog

package module
v1.4.10 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2025 License: MIT Imports: 22 Imported by: 78

README

PostHog Go

Please see the main PostHog docs.

Specifically, the Go integration details.

Quickstart

Install posthog to your gopath

$ go get github.com/posthog/posthog-go

Go 🦔!

package main

import (
    "os"
    "github.com/posthog/posthog-go"
)

func main() {
    client := posthog.New(os.Getenv("POSTHOG_API_KEY")) // This value must be set to the project API key in PostHog
    // alternatively, you can do 
    // client, _ := posthog.NewWithConfig(
    //     os.Getenv("POSTHOG_API_KEY"),
    //     posthog.Config{
    //         PersonalApiKey: "your personal API key", // Set this to your personal API token you want feature flag evaluation to be more performant.  This will incur more costs, though
    //         Endpoint:       "https://us.i.posthog.com",
    //     },
    // )
    defer client.Close()

    // Capture an event
    client.Enqueue(posthog.Capture{
      DistinctId: "test-user",
      Event:      "test-snippet",
      Properties: posthog.NewProperties().
        Set("plan", "Enterprise").
        Set("friends", 42),
    })
    
    // Add context for a user
    client.Enqueue(posthog.Identify{
      DistinctId: "user:123",
      Properties: posthog.NewProperties().
        Set("email", "john@doe.com").
        Set("proUser", false),
    })
    
    // Link user contexts
    client.Enqueue(posthog.Alias{
      DistinctId: "user:123",
      Alias: "user:12345",
    })
    
    // Capture a pageview
    client.Enqueue(posthog.Capture{
      DistinctId: "test-user",
      Event:      "$pageview",
      Properties: posthog.NewProperties().
        Set("$current_url", "https://example.com"),
    })
    
    // Capture event with calculated uuid to deduplicate repeated events. 
    // The library github.com/google/uuid is used
    key := myEvent.Id + myEvent.Project
    uid := uuid.NewSHA1(uuid.NameSpaceX500, []byte(key)).String()
    client.Enqueue(posthog.Capture{
      Uuid: uid,
      DistinctId: "test-user",
      Event:      "$pageview",
      Properties: posthog.NewProperties().
        Set("$current_url", "https://example.com"),
    })

    // Check if a feature flag is enabled
    isMyFlagEnabled, err := client.IsFeatureEnabled(
            FeatureFlagPayload{
                Key:        "flag-key",
                DistinctId: "distinct_id_of_your_user",
            })

    if isMyFlagEnabled == true {
        // Do something differently for this user
    }
}

Development

Make sure you have Go installed (macOS: brew install go, Linx / Windows: https://go.dev/doc/install).

To build the project:

# Install dependencies
make dependencies

# Run tests and build
make build

# Just run tests
make test

Testing Locally

You can run your Go app against a local build of posthog-go by making the following change to your go.mod file for whichever your app, e.g.

module example/posthog-go-app

go 1.22.5

require github.com/posthog/posthog-go v0.0.0-20240327112532-87b23fe11103

require github.com/google/uuid v1.3.0 // indirect

replace github.com/posthog/posthog-go => /path-to-your-local/posthog-go

Examples

Check out the examples for more detailed examples of how to use the PostHog Go client.

Running the examples

The examples demonstrate different features of the PostHog Go client. To run all examples:

# Set your PostHog API keys and endpoint (optional)
export POSTHOG_PROJECT_API_KEY="your-project-api-key"
export POSTHOG_PERSONAL_API_KEY="your-personal-api-key"
export POSTHOG_ENDPOINT="https://app.posthog.com"  # Optional, defaults to http://localhost:8000

# Run all examples
go run examples/*.go

This will run:

  • Feature flags example
  • Capture events example
  • Capture events with feature flag options example
Prerequisites

Before running the examples, you'll need to:

  1. Have a PostHog instance running (default: http://localhost:8000)

    • You can modify the endpoint by setting the POSTHOG_ENDPOINT environment variable
    • If not set, it defaults to "http://localhost:8000"
  2. Set up the following feature flags in your PostHog instance:

    • multivariate-test (a multivariate flag)
    • simple-test (a simple boolean flag)
    • multivariate-simple-test (a multivariate flag)
    • my_secret_flag_value (a remote config flag with string payload)
    • my_secret_flag_json_object_value (a remote config flag with JSON object payload)
    • my_secret_flag_json_array_value (a remote config flag with JSON array payload)
  3. Set your PostHog API keys as environment variables:

    • POSTHOG_PROJECT_API_KEY: Your project API key (starts with phc_...)
    • POSTHOG_PERSONAL_API_KEY: Your personal API key (starts with phx_...)

Releasing

To release a new version of the PostHog Go client, follow these steps:

  1. Update the version in the version.go file
  2. Update the changelog in CHANGELOG.md
  3. Once your changes are merged into main, create a new tag with the new version
git tag v1.4.7
git push --tags
  1. create a new release on GitHub.

Releases are installed directly from GitHub.

Questions?

Visit the community forum.

Documentation

Index

Examples

Constants

View Source
const DefaultBatchSize = 250

This constant sets the default batch size used by client instances if none was explicitly set.

View Source
const DefaultEndpoint = "https://app.posthog.com"

This constant sets the default endpoint to which client instances send messages if none was explictly set.

View Source
const DefaultFeatureFlagRequestTimeout = 3 * time.Second

Specifies the default timeout for fetching feature flags

View Source
const DefaultFeatureFlagsPollingInterval = 5 * time.Minute

Specifies the default interval at which to fetch new feature flags

View Source
const DefaultInterval = 5 * time.Second

This constant sets the default flush interval used by client instances if none was explicitly set.

View Source
const LONG_SCALE = 0xfffffffffffffff
View Source
const SIZE_DEFAULT = 50_000
View Source
const SdkName = "posthog-go"
View Source
const Version = "1.4.10"

Version of the client.

Variables

View Source
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")
)

Functions

This section is empty.

Types

type APIMessage

type APIMessage interface{}

type Alias

type Alias struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string

	Alias      string
	DistinctId string
	Timestamp  time.Time
}

This type represents object sent in a alias call

func (Alias) APIfy

func (msg Alias) APIfy() APIMessage

func (Alias) Validate

func (msg Alias) Validate() error

type AliasInApi

type AliasInApi struct {
	Type           string    `json:"type"`
	Library        string    `json:"library"`
	LibraryVersion string    `json:"library_version"`
	Timestamp      time.Time `json:"timestamp"`

	Properties AliasInApiProperties `json:"properties"`

	Event string `json:"event"`
}

type AliasInApiProperties

type AliasInApiProperties struct {
	DistinctId string `json:"distinct_id"`
	Alias      string `json:"alias"`
	Lib        string `json:"$lib"`
	LibVersion string `json:"$lib_version"`
}

type Backo

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

func DefaultBacko

func DefaultBacko() *Backo

Creates a backo instance with the following defaults:

base: 100 milliseconds
factor: 2
jitter: 0
cap: 10 seconds

func NewBacko

func NewBacko(base time.Duration, factor uint8, jitter float64, cap time.Duration) *Backo

Creates a backo instance with the given parameters

func (*Backo) Duration

func (backo *Backo) Duration(attempt int) time.Duration

Duration returns the backoff interval for the given attempt.

func (*Backo) NewTicker

func (b *Backo) NewTicker() *Ticker

func (*Backo) Sleep

func (backo *Backo) Sleep(attempt int)

Sleep pauses the current goroutine for the backoff interval for the given attempt.

type Callback

type Callback interface {

	// This method is called for every message that was successfully sent to
	// the API.
	Success(APIMessage)

	// This method is called for every message that failed to be sent to the
	// API and will be discarded by the client.
	Failure(APIMessage, error)
}

Values implementing this interface are used by posthog clients to notify the application when a message send succeeded or failed.

Callback methods are called by a client's internal goroutines, there are no guarantees on which goroutine will trigger the callbacks, the calls can be made sequentially or in parallel, the order doesn't depend on the order of messages were queued to the client.

Callback methods must return quickly and not cause long blocking operations to avoid interferring with the client's internal work flow.

type Capture

type Capture struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string
	// You don't usually need to specify this field - Posthog will generate it automatically.
	// Use it only when necessary - for example, to prevent duplicate events.
	Uuid             string
	DistinctId       string
	Event            string
	Timestamp        time.Time
	Properties       Properties
	Groups           Groups
	SendFeatureFlags bool
}

This type represents object sent in a capture call

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",
		"platform":    "macos", // :)
	},
	SendFeatureFlags: false,
})

fmt.Printf("%s\n", <-body)
Output:

{
  "api_key": "Csyjlnlun3OzyNJAafdlv",
  "batch": [
    {
      "distinct_id": "123456",
      "event": "Download",
      "library": "posthog-go",
      "library_version": "1.0.0",
      "properties": {
        "$lib": "posthog-go",
        "$lib_version": "1.0.0",
        "application": "PostHog Go",
        "platform": "macos",
        "version": "1.0.0"
      },
      "send_feature_flags": false,
      "timestamp": "2009-11-10T23:00:00Z",
      "type": "capture",
      "uuid": "00000000-0000-0000-0000-000000000000"
    }
  ]
}

func (Capture) APIfy

func (msg Capture) APIfy() APIMessage

func (Capture) Validate

func (msg Capture) Validate() error

type CaptureInApi

type CaptureInApi struct {
	Type           string    `json:"type"`
	Uuid           string    `json:"uuid"`
	Library        string    `json:"library"`
	LibraryVersion string    `json:"library_version"`
	Timestamp      time.Time `json:"timestamp"`

	DistinctId       string     `json:"distinct_id"`
	Event            string     `json:"event"`
	Properties       Properties `json:"properties"`
	SendFeatureFlags bool       `json:"send_feature_flags"`
}

type Client

type Client interface {
	io.Closer

	// 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()
	//
	// The method returns an error if the message queue could not be queued, which
	// happens if the client was already closed at the time the method was
	// called or if the message was malformed.
	Enqueue(Message) error
	//
	// Method returns if a feature flag is on for a given user based on their distinct ID
	IsFeatureEnabled(FeatureFlagPayload) (interface{}, error)
	//
	// Method returns variant value if multivariantflag or otherwise a boolean indicating
	// if the given flag is on or off for the user
	GetFeatureFlag(FeatureFlagPayload) (interface{}, error)
	//
	// Method returns feature flag payload value matching key for user (supports multivariate flags).
	GetFeatureFlagPayload(FeatureFlagPayload) (string, error)
	//
	// Method returns decrypted feature flag payload value for remote config flags.
	GetRemoteConfigPayload(string) (string, error)
	//
	// Get all flags - returns all flags for a user
	GetAllFlags(FeatureFlagPayloadNoKey) (map[string]interface{}, error)
	//
	// Method forces a reload of feature flags
	// NB: This is only available when using a PersonalApiKey
	ReloadFeatureFlags() error
	//
	// Get feature flags - for testing only
	// NB: This is only available when using a PersonalApiKey
	GetFeatureFlags() ([]FeatureFlag, error)
	//
	// Get the last captured event
	GetLastCapturedEvent() *Capture
}

This interface is the main API exposed by the posthog package. Values that satsify 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

func New(apiKey string) Client

Instantiate a new client that uses the write key passed as first argument to send messages to the backend. The client is created with the default configuration.

func NewWithConfig

func NewWithConfig(apiKey string, config Config) (cli Client, err error)

Instantiate a new client that uses the write key and configuration passed as arguments to send messages to the backend. The function will return an error if the configuration contained impossible values (like a negative flush interval for example). When the function returns an error the returned client will always be nil.

type CommonResponseFields added in v1.4.6

type CommonResponseFields struct {
	QuotaLimited              *[]string `json:"quota_limited"`
	RequestId                 string    `json:"requestId"`
	ErrorsWhileComputingFlags bool      `json:"errorsWhileComputingFlags"`
}

CommonResponseFields contains fields common to all decide response versions

type Config

type Config struct {

	// The endpoint to which the client connect and send their messages, set to
	// `DefaultEndpoint` by default.
	Endpoint string

	// Specifying a Personal API key will make feature flag evaluation more performant,
	// but it's not required for feature flags.  If you don't have a personal API key,
	// you can leave this field empty, and all of the relevant feature flag evaluation
	// methods will still work.
	// Information on how to get a personal API key: https://posthog.com/docs/api/overview
	PersonalApiKey string

	// The flushing interval of the client. Messages will be sent when they've
	// been queued up to the maximum batch size or when the flushing interval
	// timer triggers.
	Interval time.Duration

	// Interval at which to fetch new feature flag definitions, 5min by default
	DefaultFeatureFlagsPollingInterval time.Duration

	// Timeout for fetching feature flags, 3 seconds by default
	FeatureFlagRequestTimeout time.Duration

	// Calculate when feature flag definitions should be polled next. Setting this property
	// will override DefaultFeatureFlagsPollingInterval.
	NextFeatureFlagsPollingTick func() time.Duration

	// Flag to enable historical migration
	// See more in our migration docs: https://posthog.com/docs/migrate
	HistoricalMigration bool

	// The HTTP transport used by the client, this allows an application to
	// redefine how requests are being sent at the HTTP level (for example,
	// to change the connection pooling policy).
	// If none is specified the client uses `http.DefaultTransport`.
	Transport http.RoundTripper

	// The logger used by the client to output info or error messages when that
	// are generated by background operations.
	// If none is specified the client uses a standard logger that outputs to
	// `os.Stderr`.
	Logger Logger

	// Properties that will be included in every event sent by the client.
	// This is useful for adding common metadata like service name or app version across all events.
	// If a property conflict occurs, the value from DefaultEventProperties will overwrite any existing value.
	DefaultEventProperties Properties

	// The callback object that will be used by the client to notify the
	// application when messages sends to the backend API succeeded or failed.
	Callback Callback

	// The maximum number of messages that will be sent in one API call.
	// Messages will be sent when they've been queued up to the maximum batch
	// size or when the flushing interval timer triggers.
	// Note that the API will still enforce a 500KB limit on each HTTP request
	// which is independent from the number of embedded messages.
	BatchSize int

	// When set to true the client will send more frequent and detailed messages
	// to its logger.
	Verbose bool

	// The retry policy used by the client to resend requests that have failed.
	// The function is called with how many times the operation has been retried
	// and is expected to return how long the client should wait before trying
	// again.
	// If not set the client will fallback to use a default retry policy.
	RetryAfter func(int) time.Duration
	// contains filtered or unexported fields
}

Instances of this type carry the different configuration options that may be set when instantiating a client.

Each field's zero-value is either meaningful or interpreted as using the default value defined by the library.

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{}
}

Returned by the `NewWithConfig` function when the one of the configuration fields was set to an impossible value (like a negative duration).

func (ConfigError) Error

func (e ConfigError) Error() string

type DecideRequestData

type DecideRequestData struct {
	ApiKey           string                `json:"api_key"`
	DistinctId       string                `json:"distinct_id"`
	Groups           Groups                `json:"groups"`
	PersonProperties Properties            `json:"person_properties"`
	GroupProperties  map[string]Properties `json:"group_properties"`
}

type DecideResponse

type DecideResponse struct {
	CommonResponseFields

	// v4 flags format
	Flags map[string]FlagDetail `json:"flags,omitempty"`

	// v3 legacy fields
	FeatureFlags        map[string]interface{} `json:"featureFlags"`
	FeatureFlagPayloads map[string]string      `json:"featureFlagPayloads"`
}

DecideResponse represents the response from the decide endpoint v3 or v4. It is a normalized super set of the v3 and v4 formats.

func (*DecideResponse) UnmarshalJSON added in v1.4.6

func (r *DecideResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom unmarshaling to handle both v3 and v4 formats

type FeatureFlag

type FeatureFlag struct {
	Key                        string `json:"key"`
	RolloutPercentage          *uint8 `json:"rollout_percentage"`
	Active                     bool   `json:"active"`
	Filters                    Filter `json:"filters"`
	EnsureExperienceContinuity *bool  `json:"ensure_experience_continuity"`
}

type FeatureFlagCondition

type FeatureFlagCondition struct {
	Properties        []FlagProperty `json:"properties"`
	RolloutPercentage *uint8         `json:"rollout_percentage"`
	Variant           *string        `json:"variant"`
}

type FeatureFlagPayload

type FeatureFlagPayload struct {
	Key                   string
	DistinctId            string
	Groups                Groups
	PersonProperties      Properties
	GroupProperties       map[string]Properties
	OnlyEvaluateLocally   bool
	SendFeatureFlagEvents *bool
}

type FeatureFlagPayloadNoKey

type FeatureFlagPayloadNoKey struct {
	DistinctId            string
	Groups                Groups
	PersonProperties      Properties
	GroupProperties       map[string]Properties
	OnlyEvaluateLocally   bool
	SendFeatureFlagEvents *bool
}

type FeatureFlagsPoller

type FeatureFlagsPoller struct {
	Errorf   func(format string, args ...interface{})
	Endpoint string
	// contains filtered or unexported fields
}

func (*FeatureFlagsPoller) ForceReload

func (poller *FeatureFlagsPoller) ForceReload()

func (*FeatureFlagsPoller) GetAllFlags

func (poller *FeatureFlagsPoller) GetAllFlags(flagConfig FeatureFlagPayloadNoKey) (map[string]interface{}, error)

func (*FeatureFlagsPoller) GetFeatureFlag

func (poller *FeatureFlagsPoller) GetFeatureFlag(flagConfig FeatureFlagPayload) (interface{}, error)

func (*FeatureFlagsPoller) GetFeatureFlagPayload added in v1.2.16

func (poller *FeatureFlagsPoller) GetFeatureFlagPayload(flagConfig FeatureFlagPayload) (string, error)

func (*FeatureFlagsPoller) GetFeatureFlags

func (poller *FeatureFlagsPoller) GetFeatureFlags() ([]FeatureFlag, error)

type FeatureFlagsResponse

type FeatureFlagsResponse struct {
	Flags            []FeatureFlag            `json:"flags"`
	GroupTypeMapping *map[string]string       `json:"group_type_mapping"`
	Cohorts          map[string]PropertyGroup `json:"cohorts"`
}

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{}
}

Instances of this type are used to represent errors returned when a field was no initialize properly in a structure passed as argument to one of the functions of this package.

func (FieldError) Error

func (e FieldError) Error() string

type Filter

type Filter struct {
	AggregationGroupTypeIndex *uint8                 `json:"aggregation_group_type_index"`
	Groups                    []FeatureFlagCondition `json:"groups"`
	Multivariate              *Variants              `json:"multivariate"`
	Payloads                  map[string]string      `json:"payloads"`
}

type FlagDetail added in v1.4.6

type FlagDetail struct {
	Key      string       `json:"key"`
	Enabled  bool         `json:"enabled"`
	Variant  *string      `json:"variant"`
	Reason   *FlagReason  `json:"reason"`
	Metadata FlagMetadata `json:"metadata"`
}

FlagDetail represents a feature flag in v4 format

func NewFlagDetail added in v1.4.6

func NewFlagDetail(key string, value interface{}, payload *string) FlagDetail

NewFlagDetail creates a new FlagDetail from a key, value, and optional payload

func (FlagDetail) GetValue added in v1.4.6

func (f FlagDetail) GetValue() interface{}

GetValue returns the variant if it exists, otherwise returns the enabled status

type FlagMetadata added in v1.4.6

type FlagMetadata struct {
	ID          int     `json:"id"`
	Version     int     `json:"version"`
	Payload     *string `json:"payload"`
	Description *string `json:"description,omitempty"`
}

FlagMetadata contains additional information about a flag

type FlagProperty

type FlagProperty struct {
	Key      string      `json:"key"`
	Operator string      `json:"operator"`
	Value    interface{} `json:"value"`
	Type     string      `json:"type"`
	Negation bool        `json:"negation"`
}

type FlagReason added in v1.4.6

type FlagReason struct {
	Code           string `json:"code"`
	Description    string `json:"description"`
	ConditionIndex *int   `json:"condition_index"`
}

FlagReason represents why a flag was enabled/disabled

type FlagVariant

type FlagVariant struct {
	Key               string `json:"key"`
	Name              string `json:"name"`
	RolloutPercentage *uint8 `json:"rollout_percentage"`
}

type FlagVariantMeta

type FlagVariantMeta struct {
	ValueMin float64
	ValueMax float64
	Key      string
}

type GroupIdentify

type GroupIdentify struct {
	Type string
	Key  string

	DistinctId string
	Timestamp  time.Time
	Properties Properties
}

func (GroupIdentify) APIfy

func (msg GroupIdentify) APIfy() APIMessage

func (GroupIdentify) Validate

func (msg GroupIdentify) Validate() error

type GroupIdentifyInApi

type GroupIdentifyInApi struct {
	Library        string    `json:"library"`
	LibraryVersion string    `json:"library_version"`
	Timestamp      time.Time `json:"timestamp"`

	Event      string     `json:"event"`
	DistinctId string     `json:"distinct_id"`
	Properties Properties `json:"properties"`
}

type Groups

type Groups map[string]interface{}

func NewGroups

func NewGroups() Groups

func (Groups) Set

func (p Groups) Set(name string, value interface{}) Groups

type Identify

type Identify struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string

	DistinctId string
	Timestamp  time.Time
	Properties Properties
}

This type represents object sent in an identify call

func (Identify) APIfy

func (msg Identify) APIfy() APIMessage

func (Identify) Validate

func (msg Identify) Validate() error

type IdentifyInApi

type IdentifyInApi struct {
	Type           string    `json:"type"`
	Library        string    `json:"library"`
	LibraryVersion string    `json:"library_version"`
	Timestamp      time.Time `json:"timestamp"`

	Event      string     `json:"event"`
	DistinctId string     `json:"distinct_id"`
	Properties Properties `json:"properties"`
	Set        Properties `json:"$set"`
}

type InconclusiveMatchError

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

func (*InconclusiveMatchError) Error

func (e *InconclusiveMatchError) Error() string

type Logger

type Logger interface {

	// PostHog clients call this method 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{})

	// 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{})
}

Instances of types implementing this interface can be used to define where the posthog client logs are written.

func StdLogger

func StdLogger(logger *log.Logger) Logger

This function instantiate an object that statisfies the posthog.Logger interface and send logs to standard logger passed as argument.

type Message

type Message interface {

	// Validate validates the internal structure of the message, the method must return
	// nil if the message is valid, or an error describing what went wrong.
	Validate() error
	APIfy() APIMessage
	// contains filtered or unexported methods
}

This interface is used to represent posthog objects that can be sent via a client.

Types like posthog.Capture, posthog.Alias, etc... implement this interface and therefore can be passed to the posthog.Client.Send method.

type Properties

type Properties map[string]interface{}

This type 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.Page{
	DistinctId: "0123456789",
	Properties: posthog.NewProperties()
		.Set("revenue", 10.0)
		.Set("currency", "USD"),
}

func NewProperties

func NewProperties() Properties

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

type PropertyGroup

type PropertyGroup struct {
	Type string `json:"type"`
	// []PropertyGroup or []FlagProperty
	Values []any `json:"values"`
}

type SizeLimitedMap

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

type Ticker

type Ticker struct {
	C <-chan time.Time
	// contains filtered or unexported fields
}

func (*Ticker) Stop

func (t *Ticker) Stop()

type Variants

type Variants struct {
	Variants []FlagVariant `json:"variants"`
}

Directories

Path Synopsis
cmd
cli

Jump to

Keyboard shortcuts

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