usercanal
SDKs

Go SDK

Quick Start Guide for UserCanal Go SDK

Usercanal helps you track user behavior and business metrics across your applications. Our SDK provides built-in support for common analytics patterns while maintaining flexibility for custom use cases.

Quick Start (2 minutes)

1. Install the SDK

go get github.com/usercanal/sdk-go

2. Initialize the Client

import (
    "context"
    "github.com/usercanal/sdk-go"
)
 
func main() {
    canal := usercanal.NewClient("YOUR_API_KEY")
    defer canal.Close()
}

3. Track Your First Event

ctx := context.Background()
 
// Track a simple event
canal.Track(ctx, usercanal.Event{
    UserId: "123",
    Name:   usercanal.FeatureUsed,
    Properties: usercanal.Properties{
        "feature_name": "export",
        "duration_ms": 1500,
    },
})
 
// Track revenue (recommended for financial events)
canal.Revenue(ctx, usercanal.Revenue{
    OrderID:  "ord_123",
    Amount:   99.99,
    Currency: usercanal.CurrencyUSD,
    Type:     usercanal.RevenueTypeSubscription,
    Products: []usercanal.Product{
        {
            ID:       "prod_123",
            Name:     "Pro Plan",
            Price:    99.99,
            Quantity: 1,
        },
    },
})

Core Events & Types

UserCanal provides standard event names and type-safe constants for common business metrics. See all types

Event Types – Key Revenue & Conversion Events

EventDescription
OrderCompletedPurchase made
SubscriptionStartedNew subscription
SubscriptionChangedPlan changed
SubscriptionCanceledSubscription ended
CartViewedCart viewed
CheckoutStartedCheckout started
CheckoutCompletedCheckout completed

Example: Track a subscription change

canal.Track(ctx, usercanal.Event{
    UserId: "123",
    Name:   usercanal.SubscriptionChanged,
    Properties: usercanal.Properties{
        "previous_plan": "pro",
        "new_plan": "enterprise",
        "mrr_change": 199.99,
        "currency": usercanal.CurrencyUSD,
        "payment_method": usercanal.PaymentMethodCard,
    },
})

Example: Track signup

canal.Track(ctx, usercanal.Event{
    UserId: "123",
    Name:   usercanal.UserSignedUp,
    Properties: usercanal.Properties{
        "auth_method": usercanal.AuthMethodGoogle,
        "referrer": "blog",
        "utm_source": "twitter",
    },
})

User Identification

canal.Identify(ctx, usercanal.Identity{
    UserId: "123",
    Properties: usercanal.Properties{
        "name": "John Doe",
        "email": "john@example.com",
        "plan": "pro",
        "company": "Acme Inc",
    },
})

Group/Organization Tracking

canal.Group(ctx, usercanal.GroupInfo{
    UserId:  "123",
    GroupId: "org_456",
    Properties: usercanal.Properties{
        "name": "Acme Inc",
        "plan": "enterprise",
        "employee_count": 100,
    },
})

Configuration

canal := usercanal.NewClient("YOUR_API_KEY", usercanal.Config{
    BatchSize: 100,                    // Events per batch
    FlushInterval: 10 * time.Second,   // Max time between sends
    MaxRetries: 12,                    // Retry attempts
    Debug: true,                       // Enable debug logging
})

Best Practices

  1. Use Standard Events
    • Use provided constants for common events.
    • This enables automatic analytics and dashboards.
  2. Event Properties
    • Use consistent property names.
    • Include all relevant context.
    • Avoid sensitive data.
  3. Error Handling
    • Check errors from all SDK methods.
    • Use appropriate timeouts.
    • Monitor retry counts.

Debugging & Monitoring

The SDK provides built-in debugging capabilities when debug mode is enabled:

// Get current client statistics
stats := canal.GetStats()
fmt.Printf("Events in queue: %d\n", stats.EventsInQueue)
fmt.Printf("Failed events: %d\n", stats.EventsFailed)
fmt.Printf("Connection state: %s\n", stats.ConnectionState)
fmt.Printf("Connection uptime: %s\n", stats.ConnectionUptime)
 
// Print detailed status (includes connection state, event queues, etc.)
canal.DumpStatus()

Connection Monitoring

stats := canal.GetStats()
if stats.ConnectionState != "READY" {
    log.Printf("Connection not ready: %s", stats.ConnectionState)
}

Batch Processing

  • Events are automatically batched for efficiency
  • Use Flush() to force-send pending events
  • Monitor queue size with GetStats()

Complete E-commerce Example

Here's a complete example showing common e-commerce tracking patterns:

func trackEcommerceFlow() {
    canal := usercanal.NewClient("YOUR_API_KEY", usercanal.Config{
        BatchSize: 10,
        Debug: true,
    })
    defer canal.Close()
 
    ctx := context.Background()
    userId := "user_123"
    sessionId := "sess_abc123"
 
    // Track signup
    canal.Track(ctx, usercanal.Event{
        UserId: userId,
        Name:   usercanal.UserSignedUp,
        Properties: usercanal.Properties{
            "auth_method": usercanal.AuthMethodGoogle,
            "session_id": sessionId,
        },
    })
 
    // Identify user
    canal.Identify(ctx, usercanal.Identity{
        UserId: userId,
        Properties: usercanal.Properties{
            "email": "john@example.com",
            "name":  "John Doe",
        },
    })
 
    // Track product view
    canal.Track(ctx, usercanal.Event{
        UserId: userId,
        Name:   usercanal.CartViewed,
        Properties: usercanal.Properties{
            "product_id": "prod_123",
            "session_id": sessionId,
        },
    })
 
    // Track purchase
    canal.Revenue(ctx, usercanal.Revenue{
        OrderID:  "ord_123",
        Amount:   99.99,
        Currency: usercanal.CurrencyUSD,
        Type:     usercanal.RevenueTypeOneTime,
        Products: []usercanal.Product{
            {
                ID:       "prod_123",
                Name:     "Pro Plan",
                Price:    99.99,
                Quantity: 1,
            },
        },
        Properties: usercanal.Properties{
            "session_id": sessionId,
        },
    })
}

Need Help?

License

This SDK is distributed under the MIT License. See LICENSE for more information.