Go SDK

Go server-side SDK with middleware for popular frameworks

Go SDK

The github.com/entrolytics/client-go package provides a Go SDK for server-side analytics tracking with middleware support for popular web frameworks.

Installation

go get github.com/entrolytics/client-go

Quick Start

Install Package

go get github.com/entrolytics/client-go

Create a Client

package main

import (
    "log"
    entrolytics "github.com/entrolytics/client-go"
)

func main() {
    client := entrolytics.NewClient("ent_xxx")

    // Track event
    err := client.Track(entrolytics.Event{
        WebsiteID: "your-website-id",
        Name:      "purchase",
        Data: map[string]interface{}{
            "revenue":  99.99,
            "currency": "USD",
        },
    })
    if err != nil {
        log.Fatal(err)
    }
}

Track Events

// Track page view
err := client.PageView(entrolytics.PageView{
    WebsiteID: "your-website-id",
    URL:       "/pricing",
    Referrer:  "https://google.com",
    Title:     "Pricing",
})

// Identify user
err := client.Identify(entrolytics.Identify{
    WebsiteID: "your-website-id",
    UserID:    "user_456",
    Traits: map[string]interface{}{
        "email": "user@example.com",
        "plan":  "pro",
    },
})

Configuration

client := entrolytics.NewClientWithOptions(entrolytics.ClientOptions{
    APIKey:    "ent_xxx",
    Host:      "https://analytics.yourcompany.com",
    Timeout:   15 * time.Second,
    UserAgent: "my-app/1.0",
})

Framework Integrations

Standard HTTP Middleware

package main

import (
    "log"
    "net/http"
    entrolytics "github.com/entrolytics/go"
)

func trackMiddleware(next http.Handler, client *entrolytics.Client, websiteID string) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Track page view
        go func() {
            err := client.PageView(entrolytics.PageView{
                WebsiteID: websiteID,
                URL:       r.URL.String(),
                Referrer:  r.Referer(),
                UserAgent: r.UserAgent(),
                IPAddress: getClientIP(r),
            })
            if err != nil {
                log.Printf("Failed to track: %v", err)
            }
        }()

        next.ServeHTTP(w, r)
    })
}

func getClientIP(r *http.Request) string {
    if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
        return strings.Split(xff, ",")[0]
    }
    return strings.Split(r.RemoteAddr, ":")[0]
}

Context Support

All methods support context for cancellation and timeouts:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

err := client.TrackWithContext(ctx, entrolytics.Event{
    WebsiteID: "your-website-id",
    Name:      "purchase",
    Data: map[string]interface{}{
        "revenue": 99.99,
    },
})

Advanced Usage

API Reference

Types

type Event struct {
    WebsiteID  string
    Name       string
    Data       map[string]interface{}
    URL        string
    Referrer   string
    UserID     string
    SessionID  string
    UserAgent  string
    IPAddress  string
    Timestamp  *time.Time
}

type PageView struct {
    WebsiteID  string
    URL        string
    Referrer   string
    Title      string
    UserID     string
    SessionID  string
    UserAgent  string
    IPAddress  string
    Timestamp  *time.Time
}

type Identify struct {
    WebsiteID string
    UserID    string
    Traits    map[string]interface{}
    Timestamp *time.Time
}

Phase 2: Web Vitals

Track Core Web Vitals metrics:

// Track a Web Vital
err := client.TrackVital(entrolytics.WebVital{
    WebsiteID: "abc123",
    Metric:    entrolytics.LCP,
    Value:     2500.0,
    Rating:    entrolytics.Good,
    URL:       "https://example.com/page",
    Path:      "/page",
})

WebVital struct:

type WebVital struct {
    WebsiteID      string
    Metric         VitalMetric    // LCP, INP, CLS, TTFB, FCP
    Value          float64
    Rating         VitalRating    // Good, NeedsImprovement, Poor
    Delta          float64
    ID             string
    NavigationType NavigationType
    Attribution    map[string]interface{}
    URL            string
    Path           string
    SessionID      string
    Timestamp      time.Time
}

// VitalMetric constants
const (
    LCP  VitalMetric = "LCP"
    INP  VitalMetric = "INP"
    CLS  VitalMetric = "CLS"
    TTFB VitalMetric = "TTFB"
    FCP  VitalMetric = "FCP"
)

// VitalRating constants
const (
    Good             VitalRating = "good"
    NeedsImprovement VitalRating = "needs-improvement"
    Poor             VitalRating = "poor"
)

Phase 2: Form Analytics

Track form interaction events:

// Track a form submission
err := client.TrackFormEvent(entrolytics.FormEvent{
    WebsiteID:      "abc123",
    EventType:      entrolytics.FormSubmit,
    FormID:         "contact-form",
    FormName:       "Contact Form",
    URLPath:        "/contact",
    Success:        true,
    TimeSinceStart: 45000,
})

FormEvent struct:

type FormEvent struct {
    WebsiteID      string
    EventType      FormEventType // FormStart, FieldFocus, FieldBlur, FieldError, FormSubmit, FormAbandon
    FormID         string
    FormName       string
    URLPath        string
    FieldName      string
    FieldType      string
    FieldIndex     int
    TimeOnField    int
    TimeSinceStart int
    ErrorMessage   string
    Success        bool
    SessionID      string
    Timestamp      time.Time
}

// FormEventType constants
const (
    FormStart   FormEventType = "start"
    FieldFocus  FormEventType = "field_focus"
    FieldBlur   FormEventType = "field_blur"
    FieldError  FormEventType = "field_error"
    FormSubmit  FormEventType = "submit"
    FormAbandon FormEventType = "abandon"
)

Phase 2: Deployment Tracking

Register deployment context:

// Set deployment context
err := client.SetDeployment(entrolytics.Deployment{
    WebsiteID: "abc123",
    DeployID:  "deploy_456",
    GitSha:    "abc1234567890",
    GitBranch: "main",
    Source:    entrolytics.Vercel,
})

Deployment struct:

type Deployment struct {
    WebsiteID string
    DeployID  string
    GitSha    string
    GitBranch string
    DeployURL string
    Source    DeploymentSource
}

// DeploymentSource constants
const (
    Vercel     DeploymentSource = "vercel"
    Netlify    DeploymentSource = "netlify"
    Cloudflare DeploymentSource = "cloudflare"
    Railway    DeploymentSource = "railway"
    Render     DeploymentSource = "render"
    Fly        DeploymentSource = "fly"
    Heroku     DeploymentSource = "heroku"
    AWS        DeploymentSource = "aws"
    GCP        DeploymentSource = "gcp"
    Azure      DeploymentSource = "azure"
    Custom     DeploymentSource = "custom"
)

Requirements

  • Go >= 1.22

Features

  • ✅ Context support for timeouts/cancellation
  • ✅ Middleware for popular frameworks (net/http, Gin, Echo, Chi)
  • ✅ Comprehensive error types
  • ✅ Custom HTTP client support
  • ✅ Phase 2: Web Vitals tracking
  • ✅ Phase 2: Form Analytics
  • ✅ Phase 2: Deployment tracking
  • ✅ Concurrent-safe
  • ✅ Zero external dependencies (only stdlib)

Support