Go library

Last updated:

This is the official PostHog library for Go to capture and send events to any PostHog instance.

View on GitHub

This library uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your web app or other server-side application that needs performance.

Installation

go get github.com/posthog/posthog-go

Usage

package main
import (
"os"
"github.com/posthog/posthog-go"
)
func main() {
client := posthog.NewWithConfig(
os.Getenv("POSTHOG_API_KEY"),
posthog.Config{
Endpoint: "<ph_instance_address>",
PersonalApiKey: "your personal API key", // needed for feature flags
},
)
defer client.Close()
// run commands
}

Making calls

Capture

Capture allows you to capture anything a user does within your system, which you can later use in PostHog to find patterns in usage, work out which features to improve, or find out where people are giving up.

A capture call requires:

  • distinct id which uniquely identifies your user
  • event name to specify the event
    • We recommend naming events with "[noun][verb]", such as movie played or movie updated, in order to easily identify what your events mean later on (we know this from experience).

Optionally you can submit:

  • properties, which can be an array with any information you'd like to add

For example:

client.Enqueue(posthog.Capture{
DistinctId: "test-user",
Event: "test-snippet",
Properties: posthog.NewProperties().
Set("plan", "Enterprise").
Set("friends", 42),
})

Setting user properties via an event

To set properties on your users via an event, you can leverage the event properties $set and $set_once.

$set

Example

client.Enqueue(posthog.Capture{
DistinctId: "test-user",
Event: "test-snippet",
Properties: map[string]interface{}{
"eventProp": "value1",
"$set": map[string]interface{}{
"userProp": "value2",
},
}
})

Usage

When capturing an event, you can pass a property called $set as an event property, and specify its value to be an object with properties to be set on the user that will be associated with the user who triggered the event.

$set_once

Example

client.Enqueue(posthog.Capture{
DistinctId: "test-user",
Event: "test-snippet",
Properties: map[string]interface{}{
"eventProp": "value1",
"$set_once": map[string]interface{}{
"userProp": "value2",
},
}
})

Usage

$set_once works just like $set, except that it will only set the property if the user doesn't already have that property set.

Identify

We highly recommend reading our section on Identifying users to better understand how to correctly use this method.

Identify lets you add metadata to your users so you can easily identify who they are in PostHog, as well as do things like segment users by these properties.

An identify call requires:

  • distinct id which uniquely identifies your user
  • properties with a dictionary of any key:value pairs you'd like to add

For example:

client.Enqueue(posthog.Identify{
DistinctId: "user:123",
Properties: posthog.NewProperties().
Set("email", "john@doe.com").
Set("proUser", false),
})

The most obvious place to make this call is whenever a user signs up, or when they update their information.

Alias

To connect whatever a user does before they sign up or login with what they do after, you need to make an alias call. This will allow you to answer questions like "Which marketing channels lead to users churning after a month?" or "What do users do on our website before signing up?"

In a purely back-end implementation, this means whenever an anonymous user does something, you'll want to send a session ID with the capture call. Then, when that users signs up, you want to do an alias call with the session ID and the newly created user ID.

The same concept applies for when a user logs in.

If you're using PostHog in the front-end and back-end, doing the identify call in the frontend will be enough.

An alias call requires

  • distinct id the current unique id
  • alias the unique ID of the user before

For example:

client.Enqueue(posthog.Alias{
DistinctId: "user:123",
Alias: "user:12345",
})

Sending page views

If you're aiming for a full back-end implementation of PostHog, you can send page views from your backend, like so:

client.Enqueue(posthog.Capture{
DistinctId: "test-user",
Event: "$pageview",
Properties: posthog.NewProperties().
Set("$current_url", "https://example.com"),
})

Feature flags

Note that to use feature flags you must specify PersonalApiKey in the options passed to posthog.NewWithConfig.

Checking if a feature is enabled

To check if a feature flag is on for a given user, you can call isFeatureEnabled, passing the flag's key and the user's distinct ID. You can optionally pass a third argument to override the default result to be returned if the flag is not found. This is set to false by default.

// IsFeatureEnabled(flagKey string, distinctId string, defaultResult bool) (bool, error)
isFlagEnabledForUser, err := client.IsFeatureEnabled('flag-key', 'user distinct id', false)
if (isFlagEnabledForUser) {
// Do something differently for this user
}

If your feature flag relies entirely on rollout percentage (i.e. it has no filters), isFeatureEnabled will provide a fast response, allowing it to be used in the logic for API endpoints, for example. Flags that depend on filters require a call to the PostHog API so will take longer.

Reloading feature flags

When initializing PostHog, you can configure the interval at which feature flags are polled (fetched from the server). However, if you need to force a reload, you can use ReloadFeatureFlags:

client.ReloadFeatureFlags()
// Do something with feature flags here

Thank you

This library is largely based on the analytics-go package.