ga

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2017 License: LGPL-3.0 Imports: 14 Imported by: 0

README

Build Status codecov Go Report Card GoDoc

GA

Report events to google analytics with the Measurement Protocol.

GA doesn't contain helper types for GA parameters. Their API might change/grow and maintaining API parity would cost me too much time.

It does expose a simple and effective means to batch report. Report doesn't block which makes it great for server-side reporting where you do not want to spawn a network call for each incoming request.

Report will add events to a slice. After X time (you can adjust this) the events will be submitted to GA. If 20 or more events are reported before X time has passed it will immediately submit the events, as 20 is the max batch size.


Simple Usage
func main() {
	// create a Client
	c := &ga.Client{}

	// start a go routine to handle Events
	go func() {

		// Start the Client
		err := c.Start()
		if err != nil && err != ga.ErrClientClosed {
			fmt.Println(err)
			return
		}
	}()

	// report an Event
	c.Report(&ga.Event{
		"t": "pageview",
		// ...
	})

	// or report like so
	e := &ga.Event{}
	e.Set("t", "pageview")
	c.Report(e)

	// Shutdown the Client
	err := c.Shutdown(context.Background())
	if err != nil {
		fmt.Println(err)
		return
	}
}

Measurement Protocol Reference

reference


see tests and examples for more details

Documentation

Index

Examples

Constants

View Source
const ErrAlreadyStarted = Error("ga client already started")

ErrAlreadyStarted occurs when multiple Client.Start() calls are made.

View Source
const ErrClientClosed = Error("ga client closed")

ErrClientClosed occurs after a Client was closed and a new action was attempted. It is also returned by Client.Start()

View Source
const ErrGoogleAnalytics = Error("google analytics api error")

ErrGoogleAnalytics occurs when POST calls to Google Analytics fail.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// How long the client waits before reporting an Event to GA.
	// The default is 15 seconds.
	BatchWait time.Duration
	// HTTP is the http.Client used to make POST calls to GA.
	HTTP *http.Client
	// The time to wait for batch sends to complete.
	// If the timeout is exceeded the remaining items will be reported later.
	// Client.Shutdown will wait in steps of SendTimeout until all Events have been submitted.
	// The defaults to http.Client.Timeout if this is zero it will default to 5 seconds.
	SendTimeout time.Duration
	// The GA ID for Events.
	// This is only used by Client.DefaultHTTPHandler.
	TID string
	// contains filtered or unexported fields
}

Client reports Events to GA.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/romainmenke/ga"
)

func main() {

	// zero Client is good as is.
	c := &ga.Client{}

	go func() {
		err := c.Start()
		if err != nil && err != ga.ErrClientClosed {
			fmt.Println(err)
			return
		}
	}()

	time.Sleep(time.Millisecond * 5)

	c.Report(ga.Event{
		"foo": "baz",
	})

	e := ga.Event{}
	e.Set("t", "pageview")
	c.Report(e)

	err := c.Shutdown(context.Background())
	if err != nil {
		fmt.Println(err)
		return
	}
}
Output:

func (*Client) DefaultHTTPHandler

func (c *Client) DefaultHTTPHandler(h http.Handler) http.Handler

DefaultHTTPHandler attempts to provide a sane default HTTPHandler to report pageview events. For this to work the TID of the Client must be set.

Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/romainmenke/ga"
)

func main() {

	c := &ga.Client{
		TID: "some tid",
	}

	myHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// do server stuff
	})

	wrappedHandler := c.DefaultHTTPHandler(myHandler)

	http.Handle("/", wrappedHandler)

	go func() {
		err := c.Start()
		if err != nil && err != ga.ErrClientClosed {
			fmt.Println(err)
			return
		}
	}()

	time.Sleep(time.Millisecond * 5)

	c.Report(ga.Event{
		"foo": "baz",
	})

	err := c.Shutdown(context.Background())
	if err != nil {
		fmt.Println(err)
		return
	}
}
Output:

func (*Client) HandleErr

func (c *Client) HandleErr(h ErrHandler)

HandleErr sets the ErrHandler to be used by the Client. Multiple calls will override.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/pkg/errors"
	"github.com/romainmenke/ga"
)

func main() {

	c := &ga.Client{}

	// determine what happens with errors.
	c.HandleErr(ga.ErrHandlerFunc(func(events []ga.Event, err error) {
		// you can log the error
		fmt.Println(err)

		// some errs might be Wrapped
		fmt.Println(errors.Cause(err))

		// you could re-report the events here if you consider the error a temporary glitch.
		if err.Error() == "just a flesh wound" {
			for _, e := range events {
				c.Report(e)
			}
		}
	}))

	go func() {
		err := c.Start()
		if err != nil && err != ga.ErrClientClosed {
			fmt.Println(err)
			return
		}
	}()

	time.Sleep(time.Millisecond * 5)

	c.Report(ga.Event{
		"foo": "baz",
	})

	err := c.Shutdown(context.Background())
	if err != nil {
		fmt.Println(err)
		return
	}
}
Output:

func (*Client) Report

func (c *Client) Report(e Event) error

Report is used to submit an Event to GA. This can be safely called by multiple go routines.

func (*Client) Shutdown

func (c *Client) Shutdown(ctx context.Context) error

Shutdown the Client. This will block until all Events reported before calling Shutdown have been submitted.

func (*Client) Start

func (c *Client) Start() error

Start makes the Client receive Events and submit them to GA. This call will block until Client.Shutdown is called.

type ErrHandler

type ErrHandler interface {
	// Err receives the Events that erred and the corresponding error.
	// This is useful for logging and retry submitting Events.
	Err([]Event, error)
}

ErrHandler is used to handle errors that occur while submitting to GA.

type ErrHandlerFunc

type ErrHandlerFunc func(e []Event, err error)

The ErrHandlerFunc type is an adapter to allow the use of ordinary functions as ErrHandlers. If f is a function with the appropriate signature, ErrHandlerFunc(f) is a ErrHandler that calls f.

func (ErrHandlerFunc) Err

func (f ErrHandlerFunc) Err(e []Event, err error)

Err receives the Events that erred and the corresponding error. This is useful for logging and retry submitting Events.

type Error

type Error string

Error is the ga Error type

func (Error) Error

func (e Error) Error() string

type Event

type Event map[string]string

Event represents a single Google Analytics event. It is unaware of the exact GA api but knows how to format data for GA.

func (Event) Del

func (e Event) Del(key string)

Del removes a key value pair from Event.

func (Event) Get

func (e Event) Get(key string) string

Get retrieves the value for key or an empty string.

func (Event) Set

func (e Event) Set(key, value string)

Set inserts a key value pair into Event.

func (Event) WriteTo

func (e Event) WriteTo(w io.Writer) (int64, error)

WriteTo formats the key value pairs in Event and writes them to w.

Jump to

Keyboard shortcuts

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