diff --git a/context/skills/integration/config.yaml b/context/skills/integration/config.yaml index 2699fadf..11566f0c 100644 --- a/context/skills/integration/config.yaml +++ b/context/skills/integration/config.yaml @@ -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] diff --git a/context/skills/integration/description-go-docs-only.md b/context/skills/integration/description-go-docs-only.md deleted file mode 100644 index d69f71b9..00000000 --- a/context/skills/integration/description-go-docs-only.md +++ /dev/null @@ -1,27 +0,0 @@ -# PostHog integration for {display_name} - -This skill helps you add PostHog analytics to {display_name} applications using the official PostHog Go SDK documentation. - -## Instructions - -1. Detect the existing Go app structure. Check `go.mod`, `go.sum`, `cmd/`, `internal/`, HTTP/router setup, worker entry points, and existing logging/error handling. -2. Read the reference files below before changing code. They are the source of truth for SDK installation, initialization, event capture, identification, feature flags, group analytics, and error tracking. -3. Install the SDK with `go get github.com/posthog/posthog-go` instead of manually editing `go.mod`. -4. Initialize one PostHog client per process with configuration from environment variables. Close it during graceful shutdown so queued events flush. -5. Add captures at meaningful request, job, or business-action boundaries. Use a stable `DistinctId` that matches the frontend/user identity. -6. Verify with the project's normal Go commands, such as `go test ./...`, `go vet ./...`, or the repository's existing checks. - -## Reference files - -{references} - -## Key principles - -- **Environment variables**: Always use environment variables for PostHog keys. Never hardcode them. -- **Minimal changes**: Add PostHog code alongside existing integrations. Don't replace or restructure existing code. -- **Match the docs**: Follow the Go reference's initialization, capture, feature flag, and error tracking patterns exactly. -- **Analytics contract**: Treat event names, property names, and feature flag keys as part of an analytics contract. Reuse existing names and patterns found in the project. When introducing new ones, make them clear, descriptive, and consistent with existing conventions. - -## Framework guidelines - -{commandments} diff --git a/example-apps/go/.env.example b/example-apps/go/.env.example new file mode 100644 index 00000000..399249e8 --- /dev/null +++ b/example-apps/go/.env.example @@ -0,0 +1,2 @@ +POSTHOG_PROJECT_TOKEN= +POSTHOG_HOST=https://us.i.posthog.com diff --git a/example-apps/go/.gitignore b/example-apps/go/.gitignore new file mode 100644 index 00000000..7ebcd5ac --- /dev/null +++ b/example-apps/go/.gitignore @@ -0,0 +1,5 @@ +.env + +# Compiled binary (built from `go build`) +/posthog-go-example +*.exe diff --git a/example-apps/go/README.md b/example-apps/go/README.md new file mode 100644 index 00000000..c523d951 --- /dev/null +++ b/example-apps/go/README.md @@ -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/) diff --git a/example-apps/go/go.mod b/example-apps/go/go.mod new file mode 100644 index 00000000..b900888c --- /dev/null +++ b/example-apps/go/go.mod @@ -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 +) diff --git a/example-apps/go/go.sum b/example-apps/go/go.sum new file mode 100644 index 00000000..999e7a11 --- /dev/null +++ b/example-apps/go/go.sum @@ -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= diff --git a/example-apps/go/handlers.go b/example-apps/go/handlers.go new file mode 100644 index 00000000..1302c078 --- /dev/null +++ b/example-apps/go/handlers.go @@ -0,0 +1,183 @@ +package main + +import ( + "errors" + "fmt" + "html" + "log" + "net/http" + "time" + + "github.com/posthog/posthog-go" +) + +// app holds the shared dependencies for every request handler. The single +// PostHog client lives here and is reused across all requests. +type app struct { + posthog posthog.Client +} + +// distinctId returns a stable user id for the current request, falling back to +// "anonymous" before anyone has logged in. This id is the join key for all +// analytics: it MUST match the id your frontend `posthog.identify(...)` call +// uses so server- and client-side events land on the same person. +func distinctId(r *http.Request) string { + if c, err := r.Cookie("user_id"); err == nil && c.Value != "" { + return c.Value + } + return "anonymous" +} + +// home renders the login form (or a short greeting once logged in). +func (a *app) home(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/" { + http.NotFound(w, r) + return + } + page(w, "Burrito app", fmt.Sprintf(` +
Signed in as: %s
+ +You have considered a burrito %d time(s).
+A burrito_considered event was captured for %s.
You are seeing the standard dashboard.
" + if showNewFeature { + body = "🎉 You are seeing the new dashboard feature!
" + } + page(w, "Dashboard", body+fmt.Sprintf(` +Flag new-dashboard-feature for %s: %t
User: %s
+Triggered and captured an exception: %s