Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion context/skills/integration/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,8 @@ variants:
- https://posthog.com/docs/libraries/elixir.md

- id: go
template: description-go-docs-only.md
framework: go
example_paths: example-apps/go
display_name: Go
description: PostHog integration for Go applications using the posthog-go SDK
tags: [go]
Expand Down
27 changes: 0 additions & 27 deletions context/skills/integration/description-go-docs-only.md

This file was deleted.

2 changes: 2 additions & 0 deletions example-apps/go/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
POSTHOG_PROJECT_TOKEN=
POSTHOG_HOST=https://us.i.posthog.com
5 changes: 5 additions & 0 deletions example-apps/go/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.env

# Compiled binary (built from `go build`)
/posthog-go-example
*.exe
160 changes: 160 additions & 0 deletions example-apps/go/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# PostHog Go example

This is a [Go](https://go.dev) example demonstrating PostHog integration with product analytics, feature flags, user identification, and error tracking using the server-side Go SDK and the standard library `net/http`.

## Features

- **Product analytics**: Track user events and behaviors
- **User identification**: Associate events with a user via person properties (`$set`)
- **Feature flags**: Control feature rollouts with PostHog feature flags
- **Error tracking**: Report exceptions to PostHog error tracking
- **Server-side tracking**: All tracking happens server-side with the `posthog-go` SDK
- **Single client per process**: One PostHog client for the whole app, flushed on shutdown

## Getting started

### 1. Install dependencies

```bash
go get github.com/posthog/posthog-go
```

### 2. Configure environment variables

Copy `.env.example` to `.env` and fill in your values, then export them:

```bash
export POSTHOG_PROJECT_TOKEN=your_posthog_project_token
export POSTHOG_HOST=https://us.i.posthog.com
```

Get your PostHog project token from your [PostHog project settings](https://app.posthog.com/project/settings).

### 3. Run the app

```bash
go run .
```

Open [http://localhost:8000](http://localhost:8000) with your browser to see the app.

## Project structure

```
go/
├── go.mod # Module definition and the posthog-go dependency
├── .env.example # Environment variable template
├── .gitignore
├── main.go # Entry point: server wiring + graceful shutdown
├── posthog.go # The single PostHog client (config from env)
└── handlers.go # Routes: identify, events, flags, error tracking
```

## Key integration points

### PostHog client (posthog.go)

Create **one client per process** with `posthog.NewWithConfig` and share it across every request. Never construct a new client per request — the SDK batches events on a background goroutine.

```go
client, err := posthog.NewWithConfig(projectToken, posthog.Config{
Endpoint: host,
})
```

### Configuration from the environment (posthog.go)

Read the token and host from the environment so secrets never live in source. A blank token logs a clear warning and the app keeps running.

```go
projectToken := os.Getenv("POSTHOG_PROJECT_TOKEN")

host := os.Getenv("POSTHOG_HOST")
if host == "" {
host = "https://us.i.posthog.com"
}

if projectToken == "" {
log.Println("WARNING: POSTHOG_PROJECT_TOKEN is not set. PostHog events will not be delivered.")
}
```

### User identification (handlers.go)

The Go SDK identifies a user by capturing an event whose properties include `$set` (person properties). The `DistinctId` is the stable user id and must match the id your frontend `identify` call uses.

```go
client.Enqueue(posthog.Capture{
DistinctId: userId,
Event: "user_logged_in",
Properties: posthog.NewProperties().
Set("login_method", "email").
Set("$set", map[string]any{"email": email}),
})
```

### Event tracking (handlers.go)

Capture a business event with a stable distinct id and a couple of event properties.

```go
client.Enqueue(posthog.Capture{
DistinctId: userId,
Event: "burrito_considered",
Properties: posthog.NewProperties().
Set("total_considerations", count),
})
```

### Feature flags (handlers.go)

Evaluate flags once per request with `EvaluateFlags`, then read individual flags off the returned snapshot with `IsEnabled`. This is the current API — avoid the deprecated per-flag helpers.

```go
flags, err := client.EvaluateFlags(posthog.EvaluateFlagsPayload{
DistinctId: userId,
FlagKeys: []string{"new-dashboard-feature"},
})
if err == nil {
showNewFeature := flags.IsEnabled("new-dashboard-feature")
// ... branch on showNewFeature
}
```

### Error tracking (handlers.go)

Report an exception with `posthog.NewDefaultException` (timestamp, distinct id, exception type, message) and enqueue it like any other event.

```go
if err := riskyOperation(); err != nil {
exception := posthog.NewDefaultException(
time.Now(),
userId,
"ProfileDataError",
err.Error(),
)
client.Enqueue(exception)
}
```

### Flush and shutdown (main.go)

Call `client.Close()` on shutdown so the background batch of queued events is flushed before the process exits. Here it is wired to `SIGINT`/`SIGTERM`.

```go
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop

if err := client.Close(); err != nil {
log.Printf("error closing PostHog client: %v", err)
}
```

## Learn more

- [PostHog Go integration](https://posthog.com/docs/libraries/go)
- [PostHog feature flags](https://posthog.com/docs/feature-flags)
- [PostHog error tracking](https://posthog.com/docs/error-tracking)
- [PostHog documentation](https://posthog.com/docs)
- [Go documentation](https://go.dev/doc/)
14 changes: 14 additions & 0 deletions example-apps/go/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module posthog-go-example

go 1.22

require github.com/posthog/posthog-go v1.22.0

require (
github.com/andybalholm/brotli v1.1.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/klauspost/compress v1.17.11 // indirect
golang.org/x/sys v0.21.0 // indirect
)
26 changes: 26 additions & 0 deletions example-apps/go/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posthog/posthog-go v1.22.0 h1:VNy+sMJ9MMnENr9dMSxfQt/5bB4UhwRdZfasOAghMMg=
github.com/posthog/posthog-go v1.22.0/go.mod h1://M430hNH3e8CDv4i8SJesb26816Mpa6GIZaiP4pNQU=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Loading
Loading