Skip to content

agentstation/ga4m

Repository files navigation

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

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() echo.MiddlewareFunc

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

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(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

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"`
}

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"`
}

HTTPClient interface allows for mocking of http.Client in tests

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

SendEventOption allows for optional parameters when sending events.

type SendEventOption func(*sendEventOptions)

func WithContext(ctx context.Context) SendEventOption

WithContext sets a custom context for the request.

func WithDebug(debug bool) SendEventOption

WithDebug enables or disables debug mode.

func WithSessionID(sessionID string) SendEventOption

WithSessionID sets the session ID for the event.

func WithTimestamp(timestamp time.Time) SendEventOption

WithTimestamp sets a custom timestamp for the event.

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(sessions ...Session) Session

LatestSessions compares Google Analytics sessions and returns the latest one

func ParseSessionFromEchoContext(e echo.Context) Session

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

func ParseSessionFromRequest(r *http.Request) Session

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

Generated by gomarkdoc

About

Google Analytics 4 Measurements

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published