rebrand: export Insights types instead of PostHog

Rename Go package from posthog to insights across all 80+ files.
Consumers now import as `insights "github.com/hanzoai/insights-go"`
and use insights.Client, insights.Config, insights.Capture, etc.

- Rename posthog.go -> insights.go, posthog_test.go -> insights_test.go
- Update package declaration from posthog to insights in all .go files
- Update SDKName from posthog-go to insights-go
- Update DefaultEndpoint from app.posthog.com to insights.hanzo.ai
- Update all FieldError/ConfigError type strings
- Update User-Agent headers, log prefixes, comments, and docs
- Update JSON test fixtures to match new SDK name
- Update CLI, examples, extras, and sdk_compliance_adapter
- Fix pre-existing go vet warnings (non-constant format strings)
This commit is contained in:
2026-03-13 19:54:58 -07:00
parent 9b6c1ee8fc
commit b4e1366340
81 changed files with 390 additions and 392 deletions
+24 -24
View File
@@ -4,7 +4,7 @@
[![Go Report Card](https://goreportcard.com/badge/github.com/hanzoai/insights-go)](https://goreportcard.com/report/github.com/hanzoai/insights-go)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
Go client SDK for Hanzo Insights (product analytics). Built on PostHog Go client.
Go client SDK for Hanzo Insights (product analytics).
## Install
@@ -20,23 +20,23 @@ package main
import (
"os"
posthog "github.com/hanzoai/insights-go"
insights "github.com/hanzoai/insights-go"
)
func main() {
client, _ := posthog.NewWithConfig(
client, _ := insights.NewWithConfig(
os.Getenv("INSIGHTS_API_KEY"),
posthog.Config{
insights.Config{
Endpoint: "https://insights.hanzo.ai",
},
)
defer client.Close()
// Capture an event
client.Enqueue(posthog.Capture{
client.Enqueue(insights.Capture{
DistinctId: "user-123",
Event: "purchase",
Properties: posthog.NewProperties().
Properties: insights.NewProperties().
Set("plan", "enterprise").
Set("amount", 99),
})
@@ -48,10 +48,10 @@ func main() {
### Capture Events
```go
client.Enqueue(posthog.Capture{
client.Enqueue(insights.Capture{
DistinctId: "user-123",
Event: "page_view",
Properties: posthog.NewProperties().
Properties: insights.NewProperties().
Set("$current_url", "https://example.com/pricing"),
})
```
@@ -59,9 +59,9 @@ client.Enqueue(posthog.Capture{
### Identify Users
```go
client.Enqueue(posthog.Identify{
client.Enqueue(insights.Identify{
DistinctId: "user-123",
Properties: posthog.NewProperties().
Properties: insights.NewProperties().
Set("email", "[email protected]").
Set("name", "Alice").
Set("plan", "pro"),
@@ -73,7 +73,7 @@ client.Enqueue(posthog.Identify{
```go
// Check if a flag is enabled
enabled, err := client.IsFeatureEnabled(
posthog.FeatureFlagPayload{
insights.FeatureFlagPayload{
Key: "new-dashboard",
DistinctId: "user-123",
},
@@ -85,7 +85,7 @@ if enabled == true {
// Get flag variant
variant, err := client.GetFeatureFlag(
posthog.FeatureFlagPayload{
insights.FeatureFlagPayload{
Key: "checkout-flow",
DistinctId: "user-123",
},
@@ -96,19 +96,19 @@ variant, err := client.GetFeatureFlag(
```go
// Associate a user with a group
client.Enqueue(posthog.GroupIdentify{
client.Enqueue(insights.GroupIdentify{
Type: "company",
Key: "hanzo-ai",
Properties: posthog.NewProperties().
Properties: insights.NewProperties().
Set("name", "Hanzo AI").
Set("industry", "technology"),
})
// Capture event with group context
client.Enqueue(posthog.Capture{
client.Enqueue(insights.Capture{
DistinctId: "user-123",
Event: "deploy",
Groups: posthog.NewGroups().
Groups: insights.NewGroups().
Set("company", "hanzo-ai"),
})
```
@@ -116,7 +116,7 @@ client.Enqueue(posthog.Capture{
### Alias Users
```go
client.Enqueue(posthog.Alias{
client.Enqueue(insights.Alias{
DistinctId: "user-123",
Alias: "user-456",
})
@@ -125,14 +125,14 @@ client.Enqueue(posthog.Alias{
## Configuration
```go
client, _ := posthog.NewWithConfig(
client, _ := insights.NewWithConfig(
os.Getenv("INSIGHTS_API_KEY"),
posthog.Config{
insights.Config{
Endpoint: "https://insights.hanzo.ai",
PersonalApiKey: os.Getenv("INSIGHTS_PERSONAL_KEY"), // For local feature flag evaluation
BatchSize: 100,
Interval: 5 * time.Second,
MaxRetries: posthog.Ptr(3),
MaxRetries: insights.Ptr(3),
RetryAfter: func(attempt int) time.Duration {
return time.Duration(100<<attempt) * time.Millisecond
},
@@ -149,15 +149,15 @@ Monitor delivery with a callback:
```go
type DeliveryLogger struct{}
func (d *DeliveryLogger) Success(msg posthog.APIMessage) {
func (d *DeliveryLogger) Success(msg insights.APIMessage) {
log.Printf("delivered: %v", msg)
}
func (d *DeliveryLogger) Failure(msg posthog.APIMessage, err error) {
func (d *DeliveryLogger) Failure(msg insights.APIMessage, err error) {
log.Printf("dropped: %v err=%v", msg, err)
}
client, _ := posthog.NewWithConfig(apiKey, posthog.Config{
client, _ := insights.NewWithConfig(apiKey, insights.Config{
Callback: &DeliveryLogger{},
})
```
@@ -172,7 +172,7 @@ make test # Run tests only
## Attribution
Based on PostHog Go. See upstream LICENSE for attribution.
Based on PostHog Go SDK. See upstream LICENSE for attribution.
## License
+3 -3
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"time"
@@ -27,7 +27,7 @@ func (msg Alias) internal() {
func (msg Alias) Validate() error {
if len(msg.DistinctId) == 0 {
return FieldError{
Type: "posthog.Alias",
Type: "insights.Alias",
Name: "DistinctId",
Value: msg.DistinctId,
}
@@ -35,7 +35,7 @@ func (msg Alias) Validate() error {
if len(msg.Alias) == 0 {
return FieldError{
Type: "posthog.Alias",
Type: "insights.Alias",
Name: "Alias",
Value: msg.Alias,
}
+3 -3
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import "testing"
@@ -14,7 +14,7 @@ func TestAliasMissingDistinctId(t *testing.T) {
t.Error("invalid error type returned when validating alias:", err)
} else if e != (FieldError{
Type: "posthog.Alias",
Type: "insights.Alias",
Name: "DistinctId",
Value: "",
}) {
@@ -34,7 +34,7 @@ func TestAliasMissingAlias(t *testing.T) {
t.Error("invalid error type returned when validating alias:", err)
} else if e != (FieldError{
Type: "posthog.Alias",
Type: "insights.Alias",
Name: "Alias",
Value: "",
}) {
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"math"
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"context"
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"fmt"
+4 -4
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"time"
@@ -74,7 +74,7 @@ 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.
// You don't usually need to specify this field - Insights will generate it automatically.
// Use it only when necessary - for example, to prevent duplicate events.
Uuid string
DistinctId string
@@ -92,7 +92,7 @@ func (msg Capture) internal() {
func (msg Capture) Validate() error {
if len(msg.Event) == 0 {
return FieldError{
Type: "posthog.Capture",
Type: "insights.Capture",
Name: "Event",
Value: msg.Event,
}
@@ -100,7 +100,7 @@ func (msg Capture) Validate() error {
if len(msg.DistinctId) == 0 {
return FieldError{
Type: "posthog.Capture",
Type: "insights.Capture",
Name: "DistinctId",
Value: msg.DistinctId,
}
+3 -3
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import "testing"
@@ -14,7 +14,7 @@ func TestCaptureMissingEvent(t *testing.T) {
t.Error("invalid error type returned when validating capture:", err)
} else if e != (FieldError{
Type: "posthog.Capture",
Type: "insights.Capture",
Name: "Event",
Value: "",
}) {
@@ -34,7 +34,7 @@ func TestCaptureMissingDistinctId(t *testing.T) {
t.Error("invalid error type returned when validating capture:", err)
} else if e != (FieldError{
Type: "posthog.Capture",
Type: "insights.Capture",
Name: "DistinctId",
Value: "",
}) {
+12 -12
View File
@@ -6,7 +6,7 @@ import (
"os"
json "github.com/goccy/go-json"
"github.com/hanzoai/insights-go"
insights "github.com/hanzoai/insights-go"
"github.com/urfave/cli"
)
@@ -19,13 +19,13 @@ func main() {
var alias string
app := cli.NewApp()
app.Name = "posthog"
app.Usage = "Call the PostHog API"
app.Name = "insights"
app.Usage = "Call the Insights API"
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: "apiKey",
Usage: "The PostHog API Key",
Usage: "The Insights API Key",
Destination: &apiKey,
},
&cli.StringFlag{
@@ -59,29 +59,29 @@ func main() {
callback := callback(make(chan error, 1))
client, err := posthog.NewWithConfig(apiKey, posthog.Config{
client, err := insights.NewWithConfig(apiKey, insights.Config{
BatchSize: 1,
Callback: callback,
})
if err != nil {
fmt.Println("could not initialize posthog client", err)
fmt.Println("could not initialize insights client", err)
os.Exit(1)
}
switch operationType {
case "capture":
client.Enqueue(posthog.Capture{
client.Enqueue(insights.Capture{
DistinctId: distinctId,
Event: event,
Properties: parseJSON(properties),
})
case "alias":
client.Enqueue(posthog.Alias{
client.Enqueue(insights.Alias{
DistinctId: distinctId,
Alias: alias,
})
case "identify":
client.Enqueue(posthog.Identify{
client.Enqueue(insights.Identify{
DistinctId: distinctId,
Properties: parseJSON(properties),
})
@@ -112,15 +112,15 @@ func parseJSON(v string) map[string]interface{} {
return m
}
// callback implements the posthog.Callback interface. It is used by the CLI
// callback implements the insights.Callback interface. It is used by the CLI
// to wait for events to be uploaded before exiting.
type callback chan error
func (c callback) Failure(m posthog.APIMessage, err error) {
func (c callback) Failure(m insights.APIMessage, err error) {
fmt.Printf("could not upload message %v due to %v\n", m, err)
c <- err
}
func (c callback) Success(_ posthog.APIMessage) {
func (c callback) Success(_ insights.APIMessage) {
c <- nil
}
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"compress/gzip"
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"fmt"
+6 -6
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"net/http"
@@ -31,7 +31,7 @@ type Config struct {
// 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
// Information on how to get a personal API key: https://insights.hanzo.ai/docs/api/overview
PersonalApiKey string
// DisableGeoIP will disable GeoIP lookup for events and when fetching feature flags
@@ -53,7 +53,7 @@ type Config struct {
NextFeatureFlagsPollingTick func() time.Duration
// Flag to enable historical migration
// See more in our migration docs: https://posthog.com/docs/migrate
// See more in our migration docs: https://insights.hanzo.ai/docs/migrate
HistoricalMigration bool
// The HTTP transport used by the client, this allows an application to
@@ -137,17 +137,17 @@ type Config struct {
}
// 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.
// It is on by default as Go is mainly used on server side.
func (c Config) GetDisableGeoIP() bool {
return c.DisableGeoIP == nil || *c.DisableGeoIP
}
const (
SDKName = "posthog-go"
SDKName = "insights-go"
// DefaultEndpoint constant sets the default endpoint to which client instances send
// messages if none was explicitly set.
DefaultEndpoint = "https://app.posthog.com"
DefaultEndpoint = "https://insights.hanzo.ai"
// DefaultInterval constant sets the default flush interval used by client instances if
// none was explicitly set.
+3 -3
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"testing"
@@ -39,13 +39,13 @@ func TestConfig_MaxRetries(t *testing.T) {
c.MaxRetries = Ptr[int](-1)
require.ErrorContains(t, c.Validate(),
"posthog.NewWithConfig: max retries out of range [0,9] (posthog.Config.MaxRetries: -1)")
"insights.NewWithConfig: max retries out of range [0,9] (insights.Config.MaxRetries: -1)")
got = makeConfig(c)
require.Equal(t, 10, got.maxAttempts)
c.MaxRetries = Ptr[int](10)
require.ErrorContains(t, c.Validate(),
"posthog.NewWithConfig: max retries out of range [0,9] (posthog.Config.MaxRetries: 10)")
"insights.NewWithConfig: max retries out of range [0,9] (insights.Config.MaxRetries: 10)")
got = makeConfig(c)
require.Equal(t, 10, got.maxAttempts)
+2 -2
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"errors"
@@ -21,7 +21,7 @@ type ConfigError struct {
}
func (e ConfigError) Error() string {
return fmt.Sprintf("posthog.NewWithConfig: %s (posthog.Config.%s: %#v)", e.Reason, e.Field, e.Value)
return fmt.Sprintf("insights.NewWithConfig: %s (insights.Config.%s: %#v)", e.Reason, e.Field, e.Value)
}
// Instances of this type are used to represent errors returned when a field was
+2 -2
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import "testing"
@@ -9,7 +9,7 @@ func TestConfigError(t *testing.T) {
Value: 42,
}
if s := e.Error(); s != "posthog.NewWithConfig: testing (posthog.Config.Answer: 42)" {
if s := e.Error(); s != "insights.NewWithConfig: testing (insights.Config.Answer: 42)" {
t.Error("invalid error message returned by config error:", s)
}
}
+5 -7
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"time"
@@ -43,8 +43,6 @@ type ExceptionStacktrace struct {
}
// 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
type StackFrame struct {
Filename string `json:"filename"`
LineNo int `json:"lineno"`
@@ -78,14 +76,14 @@ func (msg Exception) internal() { panic(unimplementedError) }
func (msg Exception) Validate() error {
if len(msg.DistinctId) == 0 {
return FieldError{
Type: "posthog.Exception",
Type: "insights.Exception",
Name: "DistinctId",
Value: msg.DistinctId,
}
}
if len(msg.ExceptionList) == 0 {
return FieldError{
Type: "posthog.Exception",
Type: "insights.Exception",
Name: "ExceptionList",
Value: []ExceptionItem{},
}
@@ -102,14 +100,14 @@ func (msg Exception) Validate() error {
func (msg ExceptionItem) Validate() error {
if msg.Type == "" {
return FieldError{
Type: "posthog.Exception",
Type: "insights.Exception",
Name: "Type",
Value: msg.Type,
}
}
if msg.Value == "" {
return FieldError{
Type: "posthog.Exception",
Type: "insights.Exception",
Name: "Value",
Value: msg.Value,
}
+6 -6
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"context"
@@ -7,7 +7,7 @@ import (
)
// SlogCaptureHandler wraps a slog.Handler and mirrors qualifying records
// to PostHog error tracking using client.Enqueue(Exception{...}).
// to Insights error tracking using client.Enqueue(Exception{...}).
type SlogCaptureHandler struct {
next slog.Handler
client EnqueueClient
@@ -17,11 +17,11 @@ type SlogCaptureHandler struct {
// NewSlogCaptureHandler creates a new log handler wrapper.
// You typically wrap your existing handler:
//
// client, err := posthog.NewWithConfig(...)
// client, err := insights.NewWithConfig(...)
// // error handling and `defer client.Close()` call
// base := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})
// logger := slog.New(posthog.NewSlogCaptureHandler(base, client,
// posthog.WithDistinctIDFn(func(ctx context.Context, r slog.Record) string {
// logger := slog.New(insights.NewSlogCaptureHandler(base, client,
// insights.WithDistinctIDFn(func(ctx context.Context, r slog.Record) string {
// return "my-user-id" // or pull from ctx
// }),
// ))
@@ -49,7 +49,7 @@ func (h *SlogCaptureHandler) Handle(ctx context.Context, r slog.Record) error {
err = h.next.Handle(ctx, r)
}
// Then, non-intrusively mirror to PostHog if configured.
// Then, non-intrusively mirror to Insights if configured.
if h.client == nil || r.Level < h.cfg.minCaptureLevel {
return err
}
+4 -4
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"context"
@@ -7,7 +7,7 @@ import (
type captureConfig struct {
// minCaptureLevel is the lowest slog.Level at which a log record
// will be sent to PostHog. Records below this level are ignored.
// will be sent to Insights. Records below this level are ignored.
// Default: slog.LevelWarn.
minCaptureLevel slog.Level
@@ -18,7 +18,7 @@ type captureConfig struct {
distinctID func(ctx context.Context, r slog.Record) string
// fingerprint optionally computes a custom exception fingerprint
// for grouping similar errors together in PostHog. If nil, PostHog will
// for grouping similar errors together in Insights. If nil, Insights will
// assign a fingerprint during processing.
fingerprint func(ctx context.Context, r slog.Record) *string
@@ -28,7 +28,7 @@ type captureConfig struct {
skip int
// stackTraceExtractor determines how stack traces are collected
// and transformed into PostHog-compatible data structures.
// and transformed into Insights-compatible data structures.
stackTraceExtractor StackTraceExtractor
// descriptionExtractor extracts a human-readable description to
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"context"
+2 -2
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"fmt"
@@ -31,7 +31,7 @@ func SimpleInAppDecider(frame runtime.Frame) bool {
// StackTraceExtractor produces a stack trace for the current goroutine to
// enrich captured exceptions with call-site context.
type StackTraceExtractor interface {
// GetStackTrace returns a PostHog-compatible stack trace.
// GetStackTrace returns an Insights-compatible stack trace.
//
// The skip parameter controls how many leading frames to omit before
// recording. Use it to drop extractor/logging internals and start at the
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"path/filepath"
+5 -5
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"reflect"
@@ -31,7 +31,7 @@ func TestException_Validate(t *testing.T) {
},
},
expectedError: FieldError{
Type: "posthog.Exception",
Type: "insights.Exception",
Name: "DistinctId",
Value: "",
},
@@ -42,7 +42,7 @@ func TestException_Validate(t *testing.T) {
Timestamp: now,
},
expectedError: FieldError{
Type: "posthog.Exception",
Type: "insights.Exception",
Name: "ExceptionList",
Value: []ExceptionItem{},
},
@@ -56,7 +56,7 @@ func TestException_Validate(t *testing.T) {
},
},
expectedError: FieldError{
Type: "posthog.Exception",
Type: "insights.Exception",
Name: "Type",
Value: "",
},
@@ -70,7 +70,7 @@ func TestException_Validate(t *testing.T) {
},
},
expectedError: FieldError{
Type: "posthog.Exception",
Type: "insights.Exception",
Name: "Value",
Value: "",
},
+22 -22
View File
@@ -10,7 +10,7 @@ import (
func TestCapture(projectAPIKey, endpoint string) {
fmt.Println("📊 Capturing basic events...")
client, _ := posthog.NewWithConfig(projectAPIKey, posthog.Config{
client, _ := insights.NewWithConfig(projectAPIKey, insights.Config{
Interval: 30 * time.Second,
BatchSize: 100,
Verbose: true,
@@ -20,11 +20,11 @@ func TestCapture(projectAPIKey, endpoint string) {
// Send a few different types of events
fmt.Println("→ Sending 'Download' event...")
if err := client.Enqueue(posthog.Capture{
if err := client.Enqueue(insights.Capture{
Event: "Download",
DistinctId: "user_123456",
Properties: map[string]interface{}{
"application": "PostHog Go",
"application": "Insights Go",
"version": "1.0.0",
"platform": "macos",
"file_size": "2.5MB",
@@ -35,12 +35,12 @@ func TestCapture(projectAPIKey, endpoint string) {
}
fmt.Println("→ Sending 'Page View' event...")
if err := client.Enqueue(posthog.Capture{
if err := client.Enqueue(insights.Capture{
Event: "$pageview",
DistinctId: "user_123456",
Properties: map[string]interface{}{
"$current_url": "https://example.com/dashboard",
"$title": "Dashboard - PostHog",
"$title": "Dashboard - Insights",
"$referrer": "https://google.com",
},
}); err != nil {
@@ -49,7 +49,7 @@ func TestCapture(projectAPIKey, endpoint string) {
}
fmt.Println("→ Sending 'Button Clicked' event...")
if err := client.Enqueue(posthog.Capture{
if err := client.Enqueue(insights.Capture{
Event: "Button Clicked",
DistinctId: "user_123456",
Properties: map[string]interface{}{
@@ -71,7 +71,7 @@ func TestCaptureWithSendFeatureFlagOption(projectAPIKey, personalAPIKey, endpoin
fmt.Println("🏁 Capturing events with feature flags...")
fmt.Println(" This demonstrates how to automatically include feature flag states with events")
client, _ := posthog.NewWithConfig(projectAPIKey, posthog.Config{
client, _ := insights.NewWithConfig(projectAPIKey, insights.Config{
Interval: 30 * time.Second,
BatchSize: 100,
Verbose: true,
@@ -81,7 +81,7 @@ func TestCaptureWithSendFeatureFlagOption(projectAPIKey, personalAPIKey, endpoin
defer client.Close()
fmt.Println("→ Sending event with SendFeatureFlags enabled...")
if err := client.Enqueue(posthog.Capture{
if err := client.Enqueue(insights.Capture{
Event: "Purchase",
DistinctId: "user_123456",
Properties: map[string]interface{}{
@@ -89,14 +89,14 @@ func TestCaptureWithSendFeatureFlagOption(projectAPIKey, personalAPIKey, endpoin
"currency": "USD",
"product": "Premium Plan",
},
SendFeatureFlags: posthog.SendFeatureFlags(true),
SendFeatureFlags: insights.SendFeatureFlags(true),
}); err != nil {
fmt.Println("❌ Error sending Purchase event:", err)
return
}
fmt.Println("→ Sending event without feature flags for comparison...")
if err := client.Enqueue(posthog.Capture{
if err := client.Enqueue(insights.Capture{
Event: "Login",
DistinctId: "user_123456",
Properties: map[string]interface{}{
@@ -120,7 +120,7 @@ func TestCaptureWithSendFeatureFlagsOptions(projectAPIKey, personalAPIKey, endpo
fmt.Println("🚀 Advanced feature flags with SendFeatureFlagsOptions...")
fmt.Println(" This demonstrates advanced feature flag evaluation with custom properties")
client, _ := posthog.NewWithConfig(projectAPIKey, posthog.Config{
client, _ := insights.NewWithConfig(projectAPIKey, insights.Config{
Interval: 30 * time.Second,
BatchSize: 100,
Verbose: true,
@@ -130,15 +130,15 @@ func TestCaptureWithSendFeatureFlagsOptions(projectAPIKey, personalAPIKey, endpo
defer client.Close()
fmt.Println("→ Sending event with custom person properties for flag evaluation...")
if err := client.Enqueue(posthog.Capture{
if err := client.Enqueue(insights.Capture{
Event: "Feature Used",
DistinctId: "premium_user_456",
Properties: map[string]interface{}{
"feature_name": "advanced_analytics",
"usage_count": 1,
},
SendFeatureFlags: &posthog.SendFeatureFlagsOptions{
PersonProperties: posthog.NewProperties().Set("plan", "premium").Set("beta_user", true),
SendFeatureFlags: &insights.SendFeatureFlagsOptions{
PersonProperties: insights.NewProperties().Set("plan", "premium").Set("beta_user", true),
},
}); err != nil {
fmt.Println("❌ Error sending feature usage event:", err)
@@ -146,18 +146,18 @@ func TestCaptureWithSendFeatureFlagsOptions(projectAPIKey, personalAPIKey, endpo
}
fmt.Println("→ Sending event with local-only evaluation and group properties...")
if err := client.Enqueue(posthog.Capture{
if err := client.Enqueue(insights.Capture{
Event: "Team Action",
DistinctId: "enterprise_user_789",
Properties: map[string]interface{}{
"action_type": "export_data",
"data_size": "50MB",
},
SendFeatureFlags: &posthog.SendFeatureFlagsOptions{
SendFeatureFlags: &insights.SendFeatureFlagsOptions{
OnlyEvaluateLocally: true,
PersonProperties: posthog.NewProperties().Set("plan", "enterprise").Set("role", "admin"),
GroupProperties: map[string]posthog.Properties{
"company": posthog.NewProperties().Set("name", "PostHog").Set("plan", "enterprise").Set("employees", 100),
PersonProperties: insights.NewProperties().Set("plan", "enterprise").Set("role", "admin"),
GroupProperties: map[string]insights.Properties{
"company": insights.NewProperties().Set("name", "Hanzo AI").Set("plan", "enterprise").Set("employees", 100),
},
},
}); err != nil {
@@ -166,16 +166,16 @@ func TestCaptureWithSendFeatureFlagsOptions(projectAPIKey, personalAPIKey, endpo
}
fmt.Println("→ Sending event with minimal local evaluation...")
if err := client.Enqueue(posthog.Capture{
if err := client.Enqueue(insights.Capture{
Event: "Quick Action",
DistinctId: "basic_user_321",
Properties: map[string]interface{}{
"action": "button_click",
"page": "homepage",
},
SendFeatureFlags: &posthog.SendFeatureFlagsOptions{
SendFeatureFlags: &insights.SendFeatureFlagsOptions{
OnlyEvaluateLocally: true,
PersonProperties: posthog.NewProperties().Set("plan", "free"),
PersonProperties: insights.NewProperties().Set("plan", "free"),
},
}); err != nil {
fmt.Println("❌ Error sending quick action event:", err)
+5 -5
View File
@@ -10,7 +10,7 @@ import (
)
func TestErrorTrackingThroughEnqueueing(projectAPIKey, endpoint string) {
client, _ := posthog.NewWithConfig(projectAPIKey, posthog.Config{
client, _ := insights.NewWithConfig(projectAPIKey, insights.Config{
Interval: 30 * time.Second,
BatchSize: 100,
Verbose: true,
@@ -28,7 +28,7 @@ func TestErrorTrackingThroughEnqueueing(projectAPIKey, endpoint string) {
return
case <-tick:
exception := posthog.NewDefaultException(
exception := insights.NewDefaultException(
time.Now(),
"distinct-id",
"Enqueued error",
@@ -43,7 +43,7 @@ func TestErrorTrackingThroughEnqueueing(projectAPIKey, endpoint string) {
}
func TestErrorTrackingThroughLogHandler(projectAPIKey, endpoint string) {
client, _ := posthog.NewWithConfig(projectAPIKey, posthog.Config{
client, _ := insights.NewWithConfig(projectAPIKey, insights.Config{
Interval: 30 * time.Second,
BatchSize: 100,
Verbose: true,
@@ -52,8 +52,8 @@ func TestErrorTrackingThroughLogHandler(projectAPIKey, endpoint string) {
defer client.Close()
baseLogHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})
log := slog.New(posthog.NewSlogCaptureHandler(baseLogHandler, client,
posthog.WithDistinctIDFn(func(ctx context.Context, r slog.Record) string {
log := slog.New(insights.NewSlogCaptureHandler(baseLogHandler, client,
insights.WithDistinctIDFn(func(ctx context.Context, r slog.Record) string {
// for demo purposes, real applications should likely pull this value from the context.
return "my-user-id"
}),
+3 -3
View File
@@ -84,7 +84,7 @@ func TestETagPolling(projectAPIKey, personalAPIKey, endpointURL string) {
wrapped: http.DefaultTransport,
}
client, err := posthog.NewWithConfig(projectAPIKey, posthog.Config{
client, err := insights.NewWithConfig(projectAPIKey, insights.Config{
PersonalApiKey: personalAPIKey,
Endpoint: endpointURL,
DefaultFeatureFlagsPollingInterval: etagPollInterval,
@@ -125,14 +125,14 @@ func TestETagPolling(projectAPIKey, personalAPIKey, endpointURL string) {
}
}
func logETagFlagState(client posthog.Client) {
func logETagFlagState(client insights.Client) {
fmt.Println(strings.Repeat("-", 40))
// Disable $feature_flag_called events to avoid /batch/ requests
sendEvents := false
// Test a flag to verify the client is working
result, err := client.IsFeatureEnabled(posthog.FeatureFlagPayload{
result, err := client.IsFeatureEnabled(insights.FeatureFlagPayload{
Key: "test-flag",
DistinctId: "test-user",
OnlyEvaluateLocally: true,
+18 -18
View File
@@ -9,7 +9,7 @@ import (
)
func TestIsFeatureEnabled(projectAPIKey, personalAPIKey, endpoint string) {
client, err := posthog.NewWithConfig(projectAPIKey, posthog.Config{
client, err := insights.NewWithConfig(projectAPIKey, insights.Config{
Interval: 30 * time.Second,
BatchSize: 100,
Verbose: true,
@@ -25,7 +25,7 @@ func TestIsFeatureEnabled(projectAPIKey, personalAPIKey, endpoint string) {
defer client.Close()
boolResult, boolErr := client.IsFeatureEnabled(
posthog.FeatureFlagPayload{
insights.FeatureFlagPayload{
Key: "multivariate-test",
DistinctId: "hello",
})
@@ -37,7 +37,7 @@ func TestIsFeatureEnabled(projectAPIKey, personalAPIKey, endpoint string) {
}
// Simple flag
simpleResult, simpleErr := client.GetFeatureFlag(posthog.FeatureFlagPayload{
simpleResult, simpleErr := client.GetFeatureFlag(insights.FeatureFlagPayload{
Key: "simple-test",
DistinctId: "hello",
})
@@ -48,7 +48,7 @@ func TestIsFeatureEnabled(projectAPIKey, personalAPIKey, endpoint string) {
}
// Multivariate flag
variantResult, variantErr := client.GetFeatureFlag(posthog.FeatureFlagPayload{
variantResult, variantErr := client.GetFeatureFlag(insights.FeatureFlagPayload{
Key: "multivariate-test",
DistinctId: "hello",
})
@@ -58,7 +58,7 @@ func TestIsFeatureEnabled(projectAPIKey, personalAPIKey, endpoint string) {
}
// Multivariate + simple flag
variantResult, variantErr = client.GetFeatureFlag(posthog.FeatureFlagPayload{
variantResult, variantErr = client.GetFeatureFlag(insights.FeatureFlagPayload{
Key: "multivariate-simple-test",
DistinctId: "hello",
})
@@ -104,7 +104,7 @@ func TestFlagDependencies(projectAPIKey, personalAPIKey, endpoint string) {
fmt.Println(" - Rollout: 100%")
fmt.Println("")
client, err := posthog.NewWithConfig(projectAPIKey, posthog.Config{
client, err := insights.NewWithConfig(projectAPIKey, insights.Config{
Interval: 30 * time.Second,
BatchSize: 100,
Verbose: false, // Disable verbose logging for cleaner output
@@ -122,10 +122,10 @@ func TestFlagDependencies(projectAPIKey, personalAPIKey, endpoint string) {
fmt.Println("→ Testing @example.com user (should satisfy dependency if flags exist)...")
// Disable automatic $feature_flag_called events for cleaner output
sendEvents := false
result1, err1 := client.IsFeatureEnabled(posthog.FeatureFlagPayload{
result1, err1 := client.IsFeatureEnabled(insights.FeatureFlagPayload{
Key: "test-flag-dependency",
DistinctId: "example_user",
PersonProperties: posthog.NewProperties().Set("email", "[email protected]"),
PersonProperties: insights.NewProperties().Set("email", "[email protected]"),
OnlyEvaluateLocally: true,
SendFeatureFlagEvents: &sendEvents,
})
@@ -137,10 +137,10 @@ func TestFlagDependencies(projectAPIKey, personalAPIKey, endpoint string) {
}
fmt.Println("→ Testing regular user (dependency should not be satisfied)...")
result2, err2 := client.IsFeatureEnabled(posthog.FeatureFlagPayload{
result2, err2 := client.IsFeatureEnabled(insights.FeatureFlagPayload{
Key: "test-flag-dependency",
DistinctId: "regular_user",
PersonProperties: posthog.NewProperties().Set("email", "[email protected]"),
PersonProperties: insights.NewProperties().Set("email", "[email protected]"),
OnlyEvaluateLocally: true,
SendFeatureFlagEvents: &sendEvents,
})
@@ -153,18 +153,18 @@ func TestFlagDependencies(projectAPIKey, personalAPIKey, endpoint string) {
fmt.Println("→ Testing beta-feature directly for comparison...")
beta1, betaErr1 := client.IsFeatureEnabled(posthog.FeatureFlagPayload{
beta1, betaErr1 := client.IsFeatureEnabled(insights.FeatureFlagPayload{
Key: "beta-feature",
DistinctId: "example_user",
PersonProperties: posthog.NewProperties().Set("email", "[email protected]"),
PersonProperties: insights.NewProperties().Set("email", "[email protected]"),
OnlyEvaluateLocally: true,
SendFeatureFlagEvents: &sendEvents,
})
beta2, betaErr2 := client.IsFeatureEnabled(posthog.FeatureFlagPayload{
beta2, betaErr2 := client.IsFeatureEnabled(insights.FeatureFlagPayload{
Key: "beta-feature",
DistinctId: "regular_user",
PersonProperties: posthog.NewProperties().Set("email", "[email protected]"),
PersonProperties: insights.NewProperties().Set("email", "[email protected]"),
OnlyEvaluateLocally: true,
SendFeatureFlagEvents: &sendEvents,
})
@@ -178,10 +178,10 @@ func TestFlagDependencies(projectAPIKey, personalAPIKey, endpoint string) {
fmt.Println("→ Testing multivariate dependency chains...")
// Test pineapple -> blue -> breaking-bad chain
dependentResult3, err3 := client.GetFeatureFlag(posthog.FeatureFlagPayload{
dependentResult3, err3 := client.GetFeatureFlag(insights.FeatureFlagPayload{
Key: "multivariate-root-flag",
DistinctId: "regular_user",
PersonProperties: posthog.NewProperties().Set("email", "[email protected]"),
PersonProperties: insights.NewProperties().Set("email", "[email protected]"),
OnlyEvaluateLocally: true,
SendFeatureFlagEvents: &sendEvents,
})
@@ -195,10 +195,10 @@ func TestFlagDependencies(projectAPIKey, personalAPIKey, endpoint string) {
}
// Test mango -> red -> the-wire chain
dependentResult4, err4 := client.GetFeatureFlag(posthog.FeatureFlagPayload{
dependentResult4, err4 := client.GetFeatureFlag(insights.FeatureFlagPayload{
Key: "multivariate-root-flag",
DistinctId: "regular_user",
PersonProperties: posthog.NewProperties().Set("email", "[email protected]"),
PersonProperties: insights.NewProperties().Set("email", "[email protected]"),
OnlyEvaluateLocally: true,
SendFeatureFlagEvents: &sendEvents,
})
+25 -25
View File
@@ -1,13 +1,13 @@
// PostHog Go library examples
// Insights Go library examples
//
// This script demonstrates various PostHog Go SDK capabilities including:
// This script demonstrates various Insights Go SDK capabilities including:
// - Basic event capture and user identification
// - Feature flag local evaluation
// - Feature flag payloads
// - Context management
//
// Setup:
// 1. Copy .env.example to .env and fill in your PostHog credentials
// 1. Copy .env.example to .env and fill in your Insights credentials
// 2. Run this script and choose from the interactive menu
package main
@@ -29,16 +29,16 @@ var (
)
func init() {
// Load .env file if it exists (similar to Python SDK)
// Load .env file if it exists
_ = godotenv.Load()
// Get configuration from environment variables
projectAPIKey = os.Getenv("POSTHOG_PROJECT_API_KEY")
personalAPIKey = os.Getenv("POSTHOG_PERSONAL_API_KEY")
endpoint = os.Getenv("POSTHOG_ENDPOINT")
projectAPIKey = os.Getenv("INSIGHTS_PROJECT_API_KEY")
personalAPIKey = os.Getenv("INSIGHTS_PERSONAL_API_KEY")
endpoint = os.Getenv("INSIGHTS_ENDPOINT")
if endpoint == "" {
endpoint = "http://localhost:8000"
endpoint = "https://insights.hanzo.ai"
}
}
@@ -63,19 +63,19 @@ func promptForInput(prompt string) string {
func checkCredentials() {
// Check if credentials are provided
if projectAPIKey == "" || personalAPIKey == "" {
fmt.Println("❌ Missing PostHog credentials!")
fmt.Println(" Please set POSTHOG_PROJECT_API_KEY and POSTHOG_PERSONAL_API_KEY environment variables")
fmt.Println("Missing Insights credentials!")
fmt.Println(" Please set INSIGHTS_PROJECT_API_KEY and INSIGHTS_PERSONAL_API_KEY environment variables")
fmt.Println(" or copy .env.example to .env and fill in your values")
fmt.Println()
if projectAPIKey == "" {
projectAPIKey = promptForInput("Enter your PostHog project API key (starts with phc_): ")
projectAPIKey = promptForInput("Enter your Insights project API key: ")
}
if personalAPIKey == "" {
personalAPIKey = promptForInput("Enter your PostHog personal API key (starts with phx_): ")
personalAPIKey = promptForInput("Enter your Insights personal API key: ")
}
} else {
fmt.Println("✅ PostHog credentials loaded successfully!")
fmt.Println("Insights credentials loaded successfully!")
fmt.Println(" Project API Key: [REDACTED]")
fmt.Println(" Personal API Key: [REDACTED]")
fmt.Printf(" Endpoint: %s\n\n", endpoint)
@@ -83,7 +83,7 @@ func checkCredentials() {
}
func showMenu() {
fmt.Println("🚀 PostHog Go SDK Demo - Choose an example to run:")
fmt.Println("Insights Go SDK Demo - Choose an example to run:")
fmt.Println()
fmt.Println("1. Basic capture examples")
fmt.Println("2. Capture with feature flags examples")
@@ -138,23 +138,23 @@ func runETagPollingExample() {
}
func runAllExamples() {
fmt.Println("\n🔄 Running all examples...")
fmt.Println("\nRunning all examples...")
fmt.Printf("\n%s BASIC CAPTURE %s\n", strings.Repeat("🔸", 20), strings.Repeat("🔸", 20))
fmt.Println("\n--- BASIC CAPTURE ---")
TestCapture(projectAPIKey, endpoint)
fmt.Printf("\n%s CAPTURE WITH FEATURE FLAGS %s\n", strings.Repeat("🔸", 15), strings.Repeat("🔸", 15))
fmt.Println("\n--- CAPTURE WITH FEATURE FLAGS ---")
TestCaptureWithSendFeatureFlagOption(projectAPIKey, personalAPIKey, endpoint)
fmt.Printf("\n%s FEATURE FLAG EVALUATION %s\n", strings.Repeat("🔸", 17), strings.Repeat("🔸", 17))
fmt.Println("\n--- FEATURE FLAG EVALUATION ---")
TestIsFeatureEnabled(projectAPIKey, personalAPIKey, endpoint)
TestErrorTrackingThroughEnqueueing(projectAPIKey, endpoint)
TestErrorTrackingThroughLogHandler(projectAPIKey, endpoint)
fmt.Printf("\n%s ADVANCED FEATURE FLAGS %s\n", strings.Repeat("🔸", 18), strings.Repeat("🔸", 18))
fmt.Println("\n--- ADVANCED FEATURE FLAGS ---")
TestCaptureWithSendFeatureFlagsOptions(projectAPIKey, personalAPIKey, endpoint)
fmt.Printf("\n%s FLAG DEPENDENCIES %s\n", strings.Repeat("🔸", 20), strings.Repeat("🔸", 20))
fmt.Println("\n--- FLAG DEPENDENCIES ---")
TestFlagDependencies(projectAPIKey, personalAPIKey, endpoint)
}
@@ -169,7 +169,7 @@ func main() {
// If not interactive, just run all examples
if !isInteractive() {
fmt.Println("🤖 Non-interactive mode detected. Running all examples...")
fmt.Println("Non-interactive mode detected. Running all examples...")
runAllExamples()
return
}
@@ -196,21 +196,21 @@ func main() {
case "7":
runAllExamples()
case "8":
fmt.Println("👋 Goodbye!")
fmt.Println("Goodbye!")
return
default:
fmt.Println("❌ Invalid choice. Please select 1-8.")
fmt.Println("Invalid choice. Please select 1-8.")
continue
}
fmt.Println("\n" + strings.Repeat("=", 60))
fmt.Println("✅ Example completed!")
fmt.Println("Example completed!")
fmt.Println(strings.Repeat("=", 60))
// Ask if user wants to run another example
again := promptForInput("\nWould you like to run another example? (y/N): ")
if strings.ToLower(again) != "y" && strings.ToLower(again) != "yes" {
fmt.Println("👋 Goodbye!")
fmt.Println("Goodbye!")
break
}
fmt.Println()
+7 -7
View File
@@ -8,7 +8,7 @@ import (
"time"
"github.com/orian/flakyhttp"
posthog "github.com/hanzoai/insights-go"
insights "github.com/hanzoai/insights-go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -64,7 +64,7 @@ func TestEOFScenarios(t *testing.T) {
callback := newTestCallback(t)
clientConfig := posthog.Config{
clientConfig := insights.Config{
Endpoint: url,
Transport: &timeoutTransport{
rt: http.DefaultTransport,
@@ -72,18 +72,18 @@ func TestEOFScenarios(t *testing.T) {
},
Interval: 50 * time.Millisecond,
BatchSize: 1,
Logger: posthog.StdLogger(log.New(os.Stderr, "[posthog] ", log.LstdFlags), true),
Logger: insights.StdLogger(log.New(os.Stderr, "[insights] ", log.LstdFlags), true),
Callback: callback,
RetryAfter: func(i int) time.Duration { return time.Millisecond },
}
if tc.disableRetries {
clientConfig.MaxRetries = posthog.Ptr[int](0)
clientConfig.MaxRetries = insights.Ptr[int](0)
}
client, err := posthog.NewWithConfig("test-api-key", clientConfig)
require.NoError(t, err, "Failed to create PostHog client")
client, err := insights.NewWithConfig("test-api-key", clientConfig)
require.NoError(t, err, "Failed to create Insights client")
err = client.Enqueue(posthog.Capture{
err = client.Enqueue(insights.Capture{
DistinctId: "testuser",
Event: "test event",
Properties: map[string]interface{}{
+6 -6
View File
@@ -8,7 +8,7 @@ import (
"time"
"github.com/orian/flakyhttp"
posthog "github.com/hanzoai/insights-go"
insights "github.com/hanzoai/insights-go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -70,7 +70,7 @@ func TestRetryBehavior(t *testing.T) {
callback := newTestCallback(t)
config := posthog.Config{
config := insights.Config{
Endpoint: url,
Transport: &timeoutTransport{
rt: http.DefaultTransport,
@@ -78,22 +78,22 @@ func TestRetryBehavior(t *testing.T) {
},
Interval: 1 * time.Millisecond,
BatchSize: 1,
Logger: posthog.StdLogger(log.New(os.Stderr, "[posthog] ", log.LstdFlags), true),
Logger: insights.StdLogger(log.New(os.Stderr, "[insights] ", log.LstdFlags), true),
Callback: callback,
RetryAfter: func(i int) time.Duration { return time.Millisecond },
}
if tc.disableRetry {
config.MaxRetries = posthog.Ptr[int](0)
config.MaxRetries = insights.Ptr[int](0)
}
if tc.retryAfter != nil {
config.RetryAfter = tc.retryAfter
}
client, err := posthog.NewWithConfig("test-api-key", config)
client, err := insights.NewWithConfig("test-api-key", config)
require.NoError(t, err)
err = client.Enqueue(posthog.Capture{
err = client.Enqueue(insights.Capture{
DistinctId: "user1",
Event: "test_event",
})
+9 -9
View File
@@ -8,7 +8,7 @@ import (
"time"
"github.com/orian/flakyhttp"
posthog "github.com/hanzoai/insights-go"
insights "github.com/hanzoai/insights-go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -57,9 +57,9 @@ func TestTCPDropRecovery(t *testing.T) {
callback := newTestCallback(t)
client, err := posthog.NewWithConfig(
client, err := insights.NewWithConfig(
"test-api-key",
posthog.Config{
insights.Config{
Endpoint: url,
Transport: &timeoutTransport{
rt: http.DefaultTransport,
@@ -68,13 +68,13 @@ func TestTCPDropRecovery(t *testing.T) {
RetryAfter: func(i int) time.Duration { return time.Millisecond },
Interval: 10 * time.Millisecond,
BatchSize: 1,
Logger: posthog.StdLogger(log.New(os.Stderr, "[posthog] ", log.LstdFlags), true),
Logger: insights.StdLogger(log.New(os.Stderr, "[insights] ", log.LstdFlags), true),
Callback: callback,
},
)
require.NoError(t, err, "Failed to create client")
err = client.Enqueue(posthog.Capture{
err = client.Enqueue(insights.Capture{
DistinctId: "user1",
Event: "tcp_drop_recovery_test",
})
@@ -153,9 +153,9 @@ func TestTCPDropFailure(t *testing.T) {
callback := newTestCallback(t)
client, err := posthog.NewWithConfig(
client, err := insights.NewWithConfig(
"test-api-key",
posthog.Config{
insights.Config{
Endpoint: url,
Transport: &timeoutTransport{
rt: http.DefaultTransport,
@@ -164,13 +164,13 @@ func TestTCPDropFailure(t *testing.T) {
Interval: 50 * time.Millisecond,
BatchSize: 1,
RetryAfter: func(i int) time.Duration { return time.Millisecond },
Logger: posthog.StdLogger(log.New(os.Stderr, "[posthog] ", log.LstdFlags), true),
Logger: insights.StdLogger(log.New(os.Stderr, "[insights] ", log.LstdFlags), true),
Callback: callback,
},
)
require.NoError(t, err, "Failed to create client")
err = client.Enqueue(posthog.Capture{
err = client.Enqueue(insights.Capture{
DistinctId: "user1",
Event: "tcp_drop_failure_test",
})
+6 -6
View File
@@ -7,7 +7,7 @@ import (
"testing"
"time"
posthog "github.com/hanzoai/insights-go"
insights "github.com/hanzoai/insights-go"
)
// timeoutTransport wraps an http.RoundTripper with a timeout.
@@ -22,26 +22,26 @@ func (t *timeoutTransport) RoundTrip(req *http.Request) (*http.Response, error)
return t.rt.RoundTrip(req.WithContext(ctx))
}
// testCallback implements posthog.Callback to track success/failure in tests.
// testCallback implements insights.Callback to track success/failure in tests.
type testCallback struct {
t *testing.T
mu sync.Mutex
successCount int
failureCount int
lastError error
successChan chan posthog.APIMessage
successChan chan insights.APIMessage
failureChan chan error
}
func newTestCallback(t *testing.T) *testCallback {
return &testCallback{
t: t,
successChan: make(chan posthog.APIMessage, 100),
successChan: make(chan insights.APIMessage, 100),
failureChan: make(chan error, 100),
}
}
func (c *testCallback) Success(msg posthog.APIMessage) {
func (c *testCallback) Success(msg insights.APIMessage) {
c.mu.Lock()
c.successCount++
c.mu.Unlock()
@@ -49,7 +49,7 @@ func (c *testCallback) Success(msg posthog.APIMessage) {
c.successChan <- msg
}
func (c *testCallback) Failure(msg posthog.APIMessage, err error) {
func (c *testCallback) Failure(msg insights.APIMessage, err error) {
c.mu.Lock()
c.failureCount++
c.lastError = err
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
type FeatureFlagPayload struct {
Key string
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"context"
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"net/http"
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"net/http"
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"testing"
+3 -3
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"errors"
@@ -96,7 +96,7 @@ func TestFlags(t *testing.T) {
}{
{name: "IsFeatureEnabled", flagKey: "enabled-flag", expected: true},
{name: "IsFeatureEnabled", flagKey: "disabled-flag", expected: false},
{name: "IsFeatureEnabled", flagKey: "non-existent-flag", expected: false}, // Note: This differs from posthog-node which returns undefined for non-existent flags
{name: "IsFeatureEnabled", flagKey: "non-existent-flag", expected: false}, // Note: This differs from insights-node which returns undefined for non-existent flags
}
for _, subTest := range subTests {
@@ -136,7 +136,7 @@ func TestFlags(t *testing.T) {
{name: "GetFeatureFlag", flagKey: "enabled-flag", expected: true},
{name: "GetFeatureFlag", flagKey: "disabled-flag", expected: false},
{name: "GetFeatureFlag", flagKey: "multi-variate-flag", expected: "hello"},
{name: "GetFeatureFlag", flagKey: "non-existent-flag", expected: false}, // Note: This differs from posthog-node which returns undefined for non-existent flags
{name: "GetFeatureFlag", flagKey: "non-existent-flag", expected: false}, // Note: This differs from insights-node which returns undefined for non-existent flags
}
for _, subTest := range subTests {
+2 -2
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"bytes"
@@ -4297,7 +4297,7 @@ func TestFlagDefinitionsWithTimeoutExceeded(t *testing.T) {
PersonalApiKey: "some very secret key",
Endpoint: server.URL,
FeatureFlagRequestTimeout: 100 * time.Millisecond,
Logger: StdLogger(log.New(&buf, "posthog-test", log.LstdFlags), false),
Logger: StdLogger(log.New(&buf, "insights-test", log.LstdFlags), false),
})
if clientErr != nil {
t.Fatalf("Client creation failed: %v", clientErr)
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"errors"
+46 -46
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"context"
@@ -30,12 +30,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
result := c.getFeatureFlagFromRemote("test-flag", "user-123", nil, nil, nil, nil)
if result.Err != nil {
@@ -70,12 +70,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
result := c.getFeatureFlagFromRemote("variant-flag", "user-123", nil, nil, nil, nil)
if result.Err != nil {
@@ -95,12 +95,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
result := c.getFeatureFlagFromRemote("missing-flag", "user-123", nil, nil, nil, nil)
if result.Err != nil {
@@ -129,12 +129,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
result := c.getFeatureFlagFromRemote("test-flag", "user-123", nil, nil, nil, nil)
if result.Err != nil {
@@ -163,12 +163,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
result := c.getFeatureFlagFromRemote("test-flag", "user-123", nil, nil, nil, nil)
if result.Err != nil {
@@ -185,12 +185,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
result := c.getFeatureFlagFromRemote("test-flag", "user-123", nil, nil, nil, nil)
if result.Err == nil {
@@ -213,12 +213,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
result := c.getFeatureFlagFromRemote("test-flag", "user-123", nil, nil, nil, nil)
if result.Err == nil {
@@ -237,12 +237,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
result := c.getFeatureFlagFromRemote("test-flag", "user-123", nil, nil, nil, nil)
if result.Err == nil {
@@ -251,12 +251,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
})
t.Run("returns error when server is unreachable", func(t *testing.T) {
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: "http://localhost:1", // Unreachable port
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
result := c.getFeatureFlagFromRemote("test-flag", "user-123", nil, nil, nil, nil)
if result.Err == nil {
@@ -326,12 +326,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
personProps := NewProperties().Set("email", "[email protected]")
c.getFeatureFlagFromRemote("test-flag", "user-123", nil, nil, personProps, nil)
@@ -351,12 +351,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
groups := Groups{"company": "posthog"}
c.getFeatureFlagFromRemote("test-flag", "user-123", nil, groups, nil, nil)
@@ -376,12 +376,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
deviceId := "device-456"
c.getFeatureFlagFromRemote("test-flag", "user-123", &deviceId, nil, nil, nil)
@@ -401,12 +401,12 @@ func TestGetFeatureFlagFromRemote(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
c.getFeatureFlagFromRemote("test-flag", "user-123", nil, nil, nil, nil)
if requestData.DeviceId != nil {
@@ -635,12 +635,12 @@ func TestFailedFlagShouldNotReturnValue(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
result := c.getFeatureFlagFromRemote("test-flag", "user-123", nil, nil, nil, nil)
if result.Err != nil {
@@ -685,12 +685,12 @@ func TestFailedFlagShouldNotReturnValue(t *testing.T) {
}))
defer server.Close()
posthog, _ := NewWithConfig("test-api-key", Config{
cli, _ := NewWithConfig("test-api-key", Config{
Endpoint: server.URL,
})
defer posthog.Close()
defer cli.Close()
c := posthog.(*client)
c := cli.(*client)
result := c.getFeatureFlagFromRemote("test-flag", "user-123", nil, nil, nil, nil)
if result.Err != nil {
+3 -3
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"bytes"
@@ -365,7 +365,7 @@ func (poller *FeatureFlagsPoller) run() {
}
}
// fetchNewFeatureFlags fetches the latest feature flag definitions from the PostHog API
// fetchNewFeatureFlags fetches the latest feature flag definitions from the Insights API
// These are used for local evaluation of feature flags and should not be confused with
// the feature flags fetched from the flags API.
func (poller *FeatureFlagsPoller) fetchNewFeatureFlags() {
@@ -413,7 +413,7 @@ func (poller *FeatureFlagsPoller) fetchNewFeatureFlags() {
groups: map[string]string{},
flagsEtag: "",
})
poller.Logger.Warnf("[FEATURE FLAGS] PostHog feature flags quota limited, resetting feature flag data. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts")
poller.Logger.Warnf("[FEATURE FLAGS] feature flags quota limited, resetting feature flag data")
return
}
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"net/http"
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"math"
+2 -2
View File
@@ -3,11 +3,11 @@
"batch": [
{
"event": "$create_alias",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$geoip_disable": true,
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"alias": "A",
"distinct_id": "B"
@@ -4,13 +4,13 @@
{
"distinct_id": "123456",
"event": "Download",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$geoip_disable": true,
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"application": "PostHog Go",
"application": "Insights Go",
"platform": "macos",
"version": "1.0.0"
},
+3 -3
View File
@@ -4,13 +4,13 @@
{
"distinct_id": "123456",
"event": "Download",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$geoip_disable": true,
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"application": "PostHog Go",
"application": "Insights Go",
"platform": "macos",
"version": "1.0.0"
},
+3 -3
View File
@@ -4,12 +4,12 @@
{
"distinct_id": "123456",
"event": "Download",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"application": "PostHog Go",
"application": "Insights Go",
"platform": "macos",
"version": "1.0.0"
},
+3 -3
View File
@@ -3,7 +3,7 @@
"batch": [
{
"event": "$exception",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$exception_list": [
@@ -11,7 +11,7 @@
"stacktrace": {
"frames": [
{
"filename": "/Users/Developer/posthog-go/examples/main.go",
"filename": "/Users/Developer/insights-go/examples/main.go",
"function": "main.main",
"in_app": true,
"lineno": 56,
@@ -26,7 +26,7 @@
}
],
"$geoip_disable": true,
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"distinct_id": "my-user-id"
},
+2 -2
View File
@@ -4,14 +4,14 @@
{
"distinct_id": "$organization_id:5",
"event": "$groupidentify",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$geoip_disable": true,
"$group_key": "id:5",
"$group_set": {},
"$group_type": "organization",
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0"
},
"timestamp": "2009-11-10T23:00:00Z",
+2 -2
View File
@@ -7,11 +7,11 @@
},
"distinct_id": "B",
"event": "$identify",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$geoip_disable": true,
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0"
},
"timestamp": "2009-11-10T23:00:00Z",
+3 -3
View File
@@ -4,13 +4,13 @@
{
"distinct_id": "123456",
"event": "Download",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$geoip_disable": true,
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"application": "PostHog Go",
"application": "Insights Go",
"platform": "macos",
"version": "1.0.0"
},
+9 -9
View File
@@ -4,13 +4,13 @@
{
"distinct_id": "123456",
"event": "Download",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$geoip_disable": true,
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"application": "PostHog Go",
"application": "Insights Go",
"version": 0
},
"send_feature_flags": false,
@@ -21,13 +21,13 @@
{
"distinct_id": "123456",
"event": "Download",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$geoip_disable": true,
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"application": "PostHog Go",
"application": "Insights Go",
"version": 1
},
"send_feature_flags": false,
@@ -38,13 +38,13 @@
{
"distinct_id": "123456",
"event": "Download",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$geoip_disable": true,
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"application": "PostHog Go",
"application": "Insights Go",
"version": 2
},
"send_feature_flags": false,
+3 -3
View File
@@ -4,13 +4,13 @@
{
"distinct_id": "123456",
"event": "Download",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$geoip_disable": true,
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"application": "PostHog Go",
"application": "Insights Go",
"platform": "macos",
"service": "api",
"version": "1.0.0"
+3 -3
View File
@@ -4,13 +4,13 @@
{
"distinct_id": "123456",
"event": "Download",
"library": "posthog-go",
"library": "insights-go",
"library_version": "1.0.0",
"properties": {
"$geoip_disable": true,
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"application": "PostHog Go",
"application": "Insights Go",
"platform": "macos",
"version": "1.0.0"
},
+3 -3
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"bytes"
@@ -215,7 +215,7 @@ func (d *flagsClient) makeFlagsRequest(distinctId string, deviceId *string, grou
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "posthog-go/"+Version)
req.Header.Set("User-Agent", SDKName+"/"+Version)
// Create a context with timeout
ctx, cancel := context.WithTimeout(context.Background(), d.featureFlagRequestTimeout)
@@ -244,7 +244,7 @@ func (d *flagsClient) makeFlagsRequest(distinctId string, deviceId *string, grou
}
if flagsResponse.ErrorsWhileComputingFlags {
d.logger.Errorf("error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices")
d.logger.Errorf("error while computing feature flags, some flags may be missing or incorrect")
}
return &flagsResponse, nil
+3 -3
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"fmt"
@@ -24,7 +24,7 @@ func (msg GroupIdentify) internal() {
func (msg GroupIdentify) Validate() error {
if len(msg.Type) == 0 {
return FieldError{
Type: "posthog.GroupIdentify",
Type: "insights.GroupIdentify",
Name: "Type",
Value: msg.Type,
}
@@ -32,7 +32,7 @@ func (msg GroupIdentify) Validate() error {
if len(msg.Key) == 0 {
return FieldError{
Type: "posthog.GroupIdentify",
Type: "insights.GroupIdentify",
Name: "Key",
Value: msg.Key,
}
+3 -3
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import "testing"
@@ -12,7 +12,7 @@ func TestGroupIdentifyMissingType(t *testing.T) {
t.Error("invalid error type returned when validating group identify:", err)
} else if e != (FieldError{
Type: "posthog.GroupIdentify",
Type: "insights.GroupIdentify",
Name: "Type",
Value: "",
}) {
@@ -30,7 +30,7 @@ func TestGroupIdentifyMissingKey(t *testing.T) {
t.Error("invalid error type returned when validating group identify:", err)
} else if e != (FieldError{
Type: "posthog.GroupIdentify",
Type: "insights.GroupIdentify",
Name: "Key",
Value: "",
}) {
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
// 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
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"github.com/stretchr/testify/require"
+2 -2
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"time"
@@ -27,7 +27,7 @@ func (msg Identify) internal() {
func (msg Identify) Validate() error {
if len(msg.DistinctId) == 0 {
return FieldError{
Type: "posthog.Identify",
Type: "insights.Identify",
Name: "DistinctId",
Value: msg.DistinctId,
}
+2 -2
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import "testing"
@@ -12,7 +12,7 @@ func TestIdentifyMissingDistinctId(t *testing.T) {
t.Error("invalid error type returned when validating identify:", err)
} else if e != (FieldError{
Type: "posthog.Identify",
Type: "insights.Identify",
Name: "DistinctId",
Value: "",
}) {
+9 -9
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"bytes"
@@ -39,9 +39,9 @@ type EnqueueClient interface {
// This is the main method you'll be using, a typical flow would look like
// this:
//
// client := posthog.New(apiKey)
// client := insights.New(apiKey)
// ...
// client.Enqueue(posthog.Capture{ ... })
// client.Enqueue(insights.Capture{ ... })
// ...
// client.Close()
//
@@ -51,7 +51,7 @@ type EnqueueClient interface {
Enqueue(Message) error
}
// Client interface is the main API exposed by the posthog package.
// Client interface is the main API exposed by the insights package.
// Values that satisfy this interface are returned by the client constructors
// provided by the package and provide a way to send messages via the HTTP API.
type Client interface {
@@ -446,7 +446,7 @@ func (c *client) IsFeatureEnabled(flagConfig FeatureFlagPayload) (interface{}, e
func (c *client) ReloadFeatureFlags() error {
if c.featureFlagsPoller == nil {
err := fmt.Errorf("cannot use feature flags: %w", ErrNoPersonalAPIKey)
c.debugf(err.Error())
c.debugf("%s", err.Error())
return err
}
c.featureFlagsPoller.ForceReload()
@@ -627,7 +627,7 @@ func (c *client) GetRemoteConfigPayload(flagKey string) (string, error) {
func (c *client) GetFeatureFlags() ([]FeatureFlag, error) {
if c.featureFlagsPoller == nil {
err := fmt.Errorf("cannot use feature flags: %w", ErrNoPersonalAPIKey)
c.Logger.Debugf(err.Error())
c.Logger.Debugf("%s", err.Error())
return nil, err
}
return c.featureFlagsPoller.GetFeatureFlags()
@@ -1128,7 +1128,7 @@ func (c *client) getFeatureVariants(distinctId string, groups Groups, personProp
func (c *client) getFeatureVariantsWithOptions(distinctId string, groups Groups, personProperties Properties, groupProperties map[string]Properties, options *SendFeatureFlagsOptions) (map[string]interface{}, error) {
if c.featureFlagsPoller == nil {
errorMessage := "specifying a PersonalApiKey is required for using feature flags"
c.Errorf(errorMessage)
c.Errorf("%s", errorMessage)
return nil, errors.New(errorMessage)
}
@@ -1171,7 +1171,7 @@ func (c *client) makeRemoteConfigRequest(flagKey string) (string, error) {
req.Header.Set("Authorization", "Bearer "+c.PersonalApiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "posthog-go/"+Version)
req.Header.Set("User-Agent", SDKName+"/"+Version)
res, err := c.http.Do(req)
if err != nil {
@@ -1202,7 +1202,7 @@ func (c *client) isFeatureFlagsQuotaLimited(flagsResponse *FlagsResponse) bool {
}
for _, limitedFeature := range flagsResponse.QuotaLimited {
if limitedFeature == "feature_flags" {
c.Logger.Warnf("[FEATURE FLAGS] PostHog feature flags quota limited. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts")
c.Logger.Warnf("[FEATURE FLAGS] feature flags quota limited")
return true
}
}
+4 -4
View File
@@ -1,10 +1,10 @@
package posthog
package insights
// Insights is an alias for Client - use Insights for new code.
// The underlying type is the posthog Client interface.
// Insights is an alias for Client, provided for convenience.
// Both insights.Insights and insights.Client refer to the same interface.
type Insights = Client
// InsightsConfig is an alias for Config - use InsightsConfig for new code.
// InsightsConfig is an alias for Config, provided for convenience.
type InsightsConfig = Config
// NewInsights creates a new Insights client. Equivalent to New.
+19 -19
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"bytes"
@@ -229,7 +229,7 @@ func ExampleCapture() {
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"application": "Insights Go",
"version": "1.0.0",
"platform": "macos", // :)
},
@@ -244,13 +244,13 @@ func ExampleCapture() {
// {
// "distinct_id": "123456",
// "event": "Download",
// "library": "posthog-go",
// "library": "insights-go",
// "library_version": "1.0.0",
// "properties": {
// "$geoip_disable": true,
// "$lib": "posthog-go",
// "$lib": "insights-go",
// "$lib_version": "1.0.0",
// "application": "PostHog Go",
// "application": "Insights Go",
// "platform": "macos",
// "version": "1.0.0"
// },
@@ -303,7 +303,7 @@ func TestEnqueue(t *testing.T) {
Type: "raw",
Frames: []StackFrame{
{
Filename: "/Users/Developer/posthog-go/examples/main.go",
Filename: "/Users/Developer/insights-go/examples/main.go",
LineNo: 56,
Function: "main.main",
InApp: true,
@@ -365,7 +365,7 @@ func TestEnqueue(t *testing.T) {
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"application": "Insights Go",
"version": "1.0.0",
"platform": "macos", // :)
},
@@ -381,7 +381,7 @@ func TestEnqueue(t *testing.T) {
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"application": "Insights Go",
"version": "1.0.0",
"platform": "macos", // :)
},
@@ -431,7 +431,7 @@ func TestEnqueue(t *testing.T) {
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"application": "Insights Go",
"version": "1.0.0",
"platform": "macos", // :)
},
@@ -634,7 +634,7 @@ func TestEnqueuingCustomTypeFails(t *testing.T) {
client := New("0123456789")
err := client.Enqueue(&customMessage{})
require.Error(t, err)
require.EqualError(t, err, "messages with custom types cannot be enqueued: *posthog.customMessage",
require.EqualError(t, err, "messages with custom types cannot be enqueued: *insights.customMessage",
"invalid/missing error when queuing unsupported message")
}
@@ -661,7 +661,7 @@ func TestCaptureWithInterval(t *testing.T) {
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"application": "Insights Go",
"version": "1.0.0",
"platform": "macos", // :)
},
@@ -698,7 +698,7 @@ func TestCaptureWithTimestamp(t *testing.T) {
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"application": "Insights Go",
"version": "1.0.0",
"platform": "macos", // :)
},
@@ -732,7 +732,7 @@ func TestCaptureWithDefaultProperties(t *testing.T) {
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"application": "Insights Go",
"version": "1.0.0",
"platform": "macos", // :)
},
@@ -774,7 +774,7 @@ func TestCaptureMany(t *testing.T) {
Event: "Download",
DistinctId: "123456",
Properties: Properties{
"application": "PostHog Go",
"application": "Insights Go",
"version": i,
},
SendFeatureFlags: SendFeatureFlags(false),
@@ -1465,7 +1465,7 @@ func TestGetFeatureFlagPayloadWithNoPersonalApiKey(t *testing.T) {
if r.Header.Get("Content-Type") != "application/json" {
t.Errorf("Expected Content-Type: application/json, got %s", r.Header.Get("Content-Type"))
}
if !strings.HasPrefix(r.Header.Get("User-Agent"), "posthog-go/") {
if !strings.HasPrefix(r.Header.Get("User-Agent"), "insights-go/") {
t.Errorf("Unexpected User-Agent: %s", r.Header.Get("User-Agent"))
}
@@ -1691,7 +1691,7 @@ func TestGetFeatureFlagWithNoPersonalApiKey(t *testing.T) {
if r.Header.Get("Content-Type") != "application/json" {
t.Errorf("Expected Content-Type: application/json, got %s", r.Header.Get("Content-Type"))
}
if !strings.HasPrefix(r.Header.Get("User-Agent"), "posthog-go/") {
if !strings.HasPrefix(r.Header.Get("User-Agent"), "insights-go/") {
t.Errorf("Unexpected User-Agent: %s", r.Header.Get("User-Agent"))
}
@@ -1828,7 +1828,7 @@ func TestGetAllFeatureFlagsWithNoPersonalApiKey(t *testing.T) {
if r.Header.Get("Content-Type") != "application/json" {
t.Errorf("Expected Content-Type: application/json, got %s", r.Header.Get("Content-Type"))
}
if !strings.HasPrefix(r.Header.Get("User-Agent"), "posthog-go/") {
if !strings.HasPrefix(r.Header.Get("User-Agent"), "insights-go/") {
t.Errorf("Unexpected User-Agent: %s", r.Header.Get("User-Agent"))
}
@@ -2146,7 +2146,7 @@ func TestCaptureSendFlags(t *testing.T) {
defer client.Close()
// Without this call client.Close hangs forever
// Ref: https://github.com/PostHog/posthog-go/issues/28
// Ref: https://github.com/hanzoai/insights-go/issues/28
client.IsFeatureEnabled(
FeatureFlagPayload{
Key: "simpleFlag",
@@ -2202,7 +2202,7 @@ func TestCaptureSendFeatureFlagsOptions(t *testing.T) {
DistinctId: "test_user",
SendFeatureFlags: &SendFeatureFlagsOptions{
GroupProperties: map[string]Properties{
"company": NewProperties().Set("name", "PostHog"),
"company": NewProperties().Set("name", "Hanzo AI"),
},
},
})
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"bytes"
+15 -15
View File
@@ -1,36 +1,36 @@
package posthog
package insights
import (
"log"
"os"
)
// Logger defines an interface for a logger used by the PostHog clientś.
// Logger defines an interface for a logger used by the Insights client.
type Logger interface {
// Debugf is called by PostHog client to log debug messages about the
// operations they perform. Messages logged by this method are usually
// tagged with an `DEBUG` log level in common logging libraries.
// Debugf is called by the Insights client to log debug messages about the
// operations it performs. Messages logged by this method are usually
// tagged with a `DEBUG` log level in common logging libraries.
Debugf(format string, args ...interface{})
// Logf is called by PostHog client to log regular messages about the
// operations they perform. Messages logged by this method are usually
// Logf is called by the Insights client to log regular messages about the
// operations it performs. Messages logged by this method are usually
// tagged with an `INFO` log level in common logging libraries.
Logf(format string, args ...interface{})
// Warnf is called by PostHog client to log warning messages about
// the operations they perform. Messages logged by this method are usually
// tagged with an `WARN` log level in common logging libraries.
// Warnf is called by the Insights client to log warning messages about
// the operations it performs. Messages logged by this method are usually
// tagged with a `WARN` log level in common logging libraries.
Warnf(format string, args ...interface{})
// Errorf is called by PostHog clients call this method to log errors
// they encounter while sending events to the backend servers.
// Errorf is called by the Insights client to log errors encountered
// 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{})
}
// This function instantiate an object that statisfies the posthog.Logger
// interface and send logs to standard logger passed as argument.
// StdLogger creates an object that satisfies the insights.Logger
// interface and sends logs to the standard logger passed as argument.
func StdLogger(logger *log.Logger, verbose bool) Logger {
return stdLogger{
logger: logger,
@@ -62,5 +62,5 @@ func (l stdLogger) Errorf(format string, args ...interface{}) {
}
func newDefaultLogger(verbose bool) Logger {
return StdLogger(log.New(os.Stderr, "posthog ", log.LstdFlags), verbose)
return StdLogger(log.New(os.Stderr, "insights ", log.LstdFlags), verbose)
}
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"bytes"
+5 -5
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"time"
@@ -7,7 +7,7 @@ import (
"github.com/google/uuid"
)
// Values implementing this interface are used by posthog clients to notify
// Values implementing this interface are used by insights 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
@@ -28,11 +28,11 @@ type Callback interface {
Failure(APIMessage, error)
}
// This interface is used to represent posthog objects that can be sent via
// This interface is used to represent insights 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.
// Types like insights.Capture, insights.Alias, etc... implement this interface
// and therefore can be passed to the insights.Client.Enqueue method.
type Message interface {
// Validate validates the internal structure of the message, the method must return
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"context"
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"io"
+5 -5
View File
@@ -1,4 +1,4 @@
package posthog
package insights
// 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
@@ -6,11 +6,11 @@ package posthog
// common fields.
// Here's a quick example of how this type is meant to be used:
//
// posthog.Page{
// insights.Capture{
// DistinctId: "0123456789",
// Properties: posthog.NewProperties()
// .Set("revenue", 10.0)
// .Set("currency", "USD"),
// Properties: insights.NewProperties().
// Set("revenue", 10.0).
// Set("currency", "USD"),
// }
type Properties map[string]interface{}
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"reflect"
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"net/http"
+11 -11
View File
@@ -10,7 +10,7 @@ import (
"sync"
"time"
"github.com/posthog/posthog-go"
insights "github.com/hanzoai/insights-go"
)
const VERSION = "1.0.0"
@@ -75,8 +75,8 @@ func (t *TrackedTransport) RoundTrip(req *http.Request) (*http.Response, error)
// AdapterState tracks SDK state for test assertions
type AdapterState struct {
mu sync.Mutex
client posthog.Client
config *posthog.Config
client insights.Client
config *insights.Config
totalEventsCaptured int
totalEventsSent int
totalRetries int
@@ -140,8 +140,8 @@ func jsonResponse(w http.ResponseWriter, data interface{}) {
func healthHandler(w http.ResponseWriter, r *http.Request) {
response := HealthResponse{
SDKName: "posthog-go",
SDKVersion: posthog.Version,
SDKName: "insights-go",
SDKVersion: insights.Version,
AdapterVersion: VERSION,
}
jsonResponse(w, response)
@@ -171,7 +171,7 @@ func initHandler(w http.ResponseWriter, r *http.Request) {
state.pendingEvents = 0
// Create new client with tracked transport
config := posthog.Config{
config := insights.Config{
Endpoint: req.Host,
Transport: &TrackedTransport{base: http.DefaultTransport, state: state},
// Set test-friendly defaults
@@ -191,13 +191,13 @@ func initHandler(w http.ResponseWriter, r *http.Request) {
}
if req.EnableCompression != nil {
if *req.EnableCompression {
config.Compression = posthog.CompressionGzip
config.Compression = insights.CompressionGzip
} else {
config.Compression = posthog.CompressionNone
config.Compression = insights.CompressionNone
}
}
client, err := posthog.NewWithConfig(req.APIKey, config)
client, err := insights.NewWithConfig(req.APIKey, config)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@@ -225,7 +225,7 @@ func captureHandler(w http.ResponseWriter, r *http.Request) {
state.mu.Unlock()
// Create capture event
capture := posthog.Capture{
capture := insights.Capture{
DistinctId: req.DistinctID,
Event: req.Event,
Properties: req.Properties,
@@ -335,6 +335,6 @@ func main() {
http.HandleFunc("/state", stateHandler)
http.HandleFunc("/reset", resetHandler)
log.Printf("Starting PostHog Go SDK adapter on port %s", port)
log.Printf("Starting Insights Go SDK adapter on port %s", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"fmt"
+5 -5
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"crypto/rand"
@@ -27,7 +27,7 @@ const (
)
// PropertyCardinalityDistribution defines realistic distribution of property counts
// Based on typical PostHog usage patterns
// Based on typical Insights usage patterns
var PropertyCardinalityDistribution = []struct {
Cardinality PropertyCardinality
Weight int // percentage of events with this cardinality
@@ -246,7 +246,7 @@ func randomHex(length int) string {
return hex.EncodeToString(bytes)[:length]
}
// Realistic event names matching PostHog patterns
// Realistic event names matching Insights patterns
var realisticEvents = []string{
"$pageview", "$autocapture", "$identify", "$pageleave",
"user_signed_up", "purchase_completed", "item_added_to_cart",
@@ -257,7 +257,7 @@ var realisticEvents = []string{
// generateVariedProperties creates realistic property payloads with moderate cardinality
func generateVariedProperties(seed int) Properties {
props := Properties{
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
"session_id": fmt.Sprintf("sess_%d", seed/100),
"page_url": fmt.Sprintf("https://app.example.com/page/%d", seed%50),
@@ -291,7 +291,7 @@ func generatePropertiesWithCardinality(seed int, cardinality PropertyCardinality
}
props := Properties{
"$lib": "posthog-go",
"$lib": "insights-go",
"$lib_version": "1.0.0",
}
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import (
"io"
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
// ptrBool returns a pointer to the given bool.
func ptrBool(b bool) *bool { return &b }
+1 -1
View File
@@ -1,7 +1,7 @@
//go:build !go1.6
// +build !go1.6
package posthog
package insights
import "net/http"
+1 -1
View File
@@ -1,7 +1,7 @@
//go:build go1.6
// +build go1.6
package posthog
package insights
import "net/http"
+1 -1
View File
@@ -1,4 +1,4 @@
package posthog
package insights
import "flag"