ga4m

package module
v0.0.0-...-3f0c66e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2024 License: MIT Imports: 10 Imported by: 0

README

                                     __ _        _  _              
                                    / _` |  __ _| || |   _ __ ___  
                                   | (_| | / _` | || |_ | '_ ` _ \ 
                                    \__, || (_| |__   _|| | | | | |
                                    |___/  \__,_|  |_|  |_| |_| |_|

This package provides a client for sending events to Google Analytics 4 via the Measurement Protocol (GA4M).

Usage Example

Here's a simple example of how to use ga4m to track page views in a web application:

package main

import (
	"fmt"
	"net/http"

	"github.com/agentstation/ga4m"
)

func handler(w http.ResponseWriter, r *http.Request) {
	// Initialize the AnalyticsClient
	gaClient := ga4m.NewClient("YOUR_MEASUREMENT_ID", "YOUR_API_SECRET")

	// Parse the GA cookies to get the session data
	session := ga4m.ParseSessionFromRequest(r)

	// Prepare event parameters
	params := map[string]string{
		"page_title": "Homepage",
		"page_path":  "/",
	}

	// Send the event
	err := gaClient.SendEvent(session, "page_view", params)
	if err != nil {
		fmt.Printf("Error sending event: %v\n", err)
	}
}

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}

This example demonstrates:

  • Creating a new GA4 client with your measurement ID and API secret
  • Parsing GA cookies from incoming HTTP requests to obtain session information
  • Sending a page view event with custom parameters using the session data
  • Automatic inclusion of session_id and engagement_time_msec in the event parameters

ga4m

import "github.com/agentstation/ga4m"

Index

Constants

const (
    // DefaultEngagementTimeMS is the default engagement time in milliseconds
    DefaultEngagementTimeMS = "100"

    // SessionIDParam is the parameter name for the session ID
    SessionIDParam = "session_id"

    // EngagementTimeParam is the parameter name for the engagement time in milliseconds
    EngagementTimeParam = "engagement_time_msec"

    // MaxEventsPerRequest is the maximum number of events per request
    MaxEventsPerRequest = 25

    // URLFormat is the format for the URL
    URLFormat = "%s?measurement_id=%s&api_secret=%s"

    // ContentTypeHeader is the header for the content type
    ContentTypeHeader = "Content-Type"

    // ContentTypeJSON is the content type for JSON
    ContentTypeJSON = "application/json"
)

const (
    // ContextKey is the key middleware uses to store the Google Analytics session in the echo context
    ContextKey = "ga4m.session"
)

Variables

EmptySession is an empty Google Analytics session

var EmptySession = Session{}

func GoogleAnalyticsCookieEchoMiddleware

func GoogleAnalyticsCookieEchoMiddleware() echo.MiddlewareFunc

GoogleAnalyticsCookieEchoMiddleware extracts user Google Analytics session data from cookies and stores it in the context for later use

type AnalyticsClient

AnalyticsClient is the client for sending events to Google Analytics

type AnalyticsClient struct {
    MeasurementID string
    APISecret     string
    Endpoint      string
    DebugEndpoint string
    HTTPClient    HTTPClient
}

func NewClient

func NewClient(measurementID, apiSecret string) *AnalyticsClient

NewClient creates a new AnalyticsClient with the provided measurement ID and API secret

func (*AnalyticsClient) SendEvent

func (c *AnalyticsClient) SendEvent(session Session, eventName string, params map[string]string, opts ...SendEventOption) error

SendEvent sends a single event to Google Analytics.

func (*AnalyticsClient) SendEvents

func (c *AnalyticsClient) SendEvents(session Session, events []EventParams, opts ...SendEventOption) error

SendEvents sends multiple events in a single batch request to Google Analytics.

func (*AnalyticsClient) SetHTTPClient

func (c *AnalyticsClient) SetHTTPClient(client HTTPClient)

SetHTTPClient allows setting a custom HTTP client

type AnalyticsEvent

AnalyticsEvent represents the payload structure for GA4 events.

type AnalyticsEvent struct {
    ClientID        string        `json:"client_id"`
    Events          []EventParams `json:"events"`
    UserID          string        `json:"user_id,omitempty"`
    TimestampMicros int64         `json:"timestamp_micros,omitempty"`
}

type EventParams

EventParams represents parameters for a GA4 event.

type EventParams struct {
    Name            string            `json:"name"`
    Params          map[string]string `json:"params,omitempty"`
    TimestampMicros int64             `json:"timestamp_micros,omitempty"`
}

type HTTPClient

HTTPClient interface allows for mocking of http.Client in tests

type HTTPClient interface {
    Do(req *http.Request) (*http.Response, error)
}

type SendEventOption

SendEventOption allows for optional parameters when sending events.

type SendEventOption func(*sendEventOptions)

func WithContext

func WithContext(ctx context.Context) SendEventOption

WithContext sets a custom context for the request.

func WithDebug

func WithDebug(debug bool) SendEventOption

WithDebug enables or disables debug mode.

func WithSessionID

func WithSessionID(sessionID string) SendEventOption

WithSessionID sets the session ID for the event.

func WithTimestamp

func WithTimestamp(timestamp time.Time) SendEventOption

WithTimestamp sets a custom timestamp for the event.

func WithUserID

func WithUserID(userID string) SendEventOption

WithUserID sets the user ID for the event.

type Session

Session represents the Google Analytics session tracking data for a user.

type Session struct {
    // Client Cookie Data
    ClientID      string    // The client ID from _ga cookie.
    ClientVersion string    // The version from _ga cookie (e.g., "1")
    FirstVisit    time.Time // First visit timestamp.

    // Session Cookie Data
    SessionCount   int       // Number of sessions.
    LastSession    time.Time // Last session timestamp.
    SessionID      string    // Unique identifier for the current session
    SessionVersion string    // The version from _ga_* cookie (e.g., "1")
    IsEngaged      bool      // Indicates if the user is actively engaged
    HitCount       int       // Number of hits/interactions in the current session
    IsFirstSession bool      // Indicates if this is the user's first session
    IsNewSession   bool      // Indicates if this is a new session
}

func LatestSessions

func LatestSessions(sessions ...Session) Session

LatestSessions compares Google Analytics sessions and returns the latest one

func ParseSessionFromEchoContext

func ParseSessionFromEchoContext(e echo.Context) Session

ParseSessionFromEchoContext returns the Google Analytics tracking data from an echo.Context

func ParseSessionFromRequest

func ParseSessionFromRequest(r *http.Request) Session

ParseSessionFromRequest parses the Google Analytics cookies from an HTTP request and returns a Session.

Generated by gomarkdoc

Documentation

Index

Constants

View Source
const (
	// DefaultEngagementTimeMS is the default engagement time in milliseconds
	DefaultEngagementTimeMS = "100"

	// SessionIDParam is the parameter name for the session ID
	SessionIDParam = "session_id"

	// EngagementTimeParam is the parameter name for the engagement time in milliseconds
	EngagementTimeParam = "engagement_time_msec"

	// MaxEventsPerRequest is the maximum number of events per request
	MaxEventsPerRequest = 25

	// URLFormat is the format for the URL
	URLFormat = "%s?measurement_id=%s&api_secret=%s"

	// ContentTypeHeader is the header for the content type
	ContentTypeHeader = "Content-Type"

	// ContentTypeJSON is the content type for JSON
	ContentTypeJSON = "application/json"
)
View Source
const (
	// ContextKey is the key middleware uses to store the Google Analytics session in the echo context
	ContextKey = "ga4m.session"
)

Variables

View Source
var EmptySession = Session{}

EmptySession is an empty Google Analytics session

Functions

func GoogleAnalyticsCookieEchoMiddleware

func GoogleAnalyticsCookieEchoMiddleware() echo.MiddlewareFunc

GoogleAnalyticsCookieEchoMiddleware extracts user Google Analytics session data from cookies and stores it in the context for later use

Types

type AnalyticsClient

type AnalyticsClient struct {
	MeasurementID string
	APISecret     string
	Endpoint      string
	DebugEndpoint string
	HTTPClient    HTTPClient
}

AnalyticsClient is the client for sending events to Google Analytics

func NewClient

func NewClient(measurementID, apiSecret string) *AnalyticsClient

NewClient creates a new AnalyticsClient with the provided measurement ID and API secret

func (*AnalyticsClient) SendEvent

func (c *AnalyticsClient) SendEvent(session Session, eventName string, params map[string]string, opts ...SendEventOption) error

SendEvent sends a single event to Google Analytics.

func (*AnalyticsClient) SendEvents

func (c *AnalyticsClient) SendEvents(session Session, events []EventParams, opts ...SendEventOption) error

SendEvents sends multiple events in a single batch request to Google Analytics.

func (*AnalyticsClient) SetHTTPClient

func (c *AnalyticsClient) SetHTTPClient(client HTTPClient)

SetHTTPClient allows setting a custom HTTP client

type AnalyticsEvent

type AnalyticsEvent struct {
	ClientID        string        `json:"client_id"`
	Events          []EventParams `json:"events"`
	UserID          string        `json:"user_id,omitempty"`
	TimestampMicros int64         `json:"timestamp_micros,omitempty"`
}

AnalyticsEvent represents the payload structure for GA4 events.

type EventParams

type EventParams struct {
	Name            string            `json:"name"`
	Params          map[string]string `json:"params,omitempty"`
	TimestampMicros int64             `json:"timestamp_micros,omitempty"`
}

EventParams represents parameters for a GA4 event.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient interface allows for mocking of http.Client in tests

type SendEventOption

type SendEventOption func(*sendEventOptions)

SendEventOption allows for optional parameters when sending events.

func WithContext

func WithContext(ctx context.Context) SendEventOption

WithContext sets a custom context for the request.

func WithDebug

func WithDebug(debug bool) SendEventOption

WithDebug enables or disables debug mode.

func WithSessionID

func WithSessionID(sessionID string) SendEventOption

WithSessionID sets the session ID for the event.

func WithTimestamp

func WithTimestamp(timestamp time.Time) SendEventOption

WithTimestamp sets a custom timestamp for the event.

func WithUserID

func WithUserID(userID string) SendEventOption

WithUserID sets the user ID for the event.

type Session

type Session struct {
	// Client Cookie Data
	ClientID      string    // The client ID from _ga cookie.
	ClientVersion string    // The version from _ga cookie (e.g., "1")
	FirstVisit    time.Time // First visit timestamp.

	// Session Cookie Data
	SessionCount   int       // Number of sessions.
	LastSession    time.Time // Last session timestamp.
	SessionID      string    // Unique identifier for the current session
	SessionVersion string    // The version from _ga_* cookie (e.g., "1")
	IsEngaged      bool      // Indicates if the user is actively engaged
	HitCount       int       // Number of hits/interactions in the current session
	IsFirstSession bool      // Indicates if this is the user's first session
	IsNewSession   bool      // Indicates if this is a new session
}

Session represents the Google Analytics session tracking data for a user.

func LatestSessions

func LatestSessions(sessions ...Session) Session

LatestSessions compares Google Analytics sessions and returns the latest one

func ParseSessionFromEchoContext

func ParseSessionFromEchoContext(e echo.Context) Session

ParseSessionFromEchoContext returns the Google Analytics tracking data from an echo.Context

func ParseSessionFromRequest

func ParseSessionFromRequest(r *http.Request) Session

ParseSessionFromRequest parses the Google Analytics cookies from an HTTP request and returns a Session.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL