analytics

package module
v2.0.1-0...-22a8b9e Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2019 License: MIT Imports: 24 Imported by: 2

README

analytics-go go-doc Build Status

Segment analytics client for Go.

This is a fork of segmentio/analytics-go library.

Notable changes:

  • Use fully customised endpoint without /v1/batch postfix
  • Use X-API-Key header for authorisation
  • Ability to report usage metrics to DataDog

Latest stable branch is master. Releases are presented on Releases page.

Installation

If you use dep then add these lines to your Gopkg.toml:

[[constraint]]
  name = "github.com/FindHotel/analytics-go"
  version = "3.4.0"  # get the latest version from Releases

Documentation

The links bellow should provide all the documentation needed to make the best use of the library and the Segment API:

Usage

package main

import (
    "os"

    analytics "github.com/FindHotel/analytics-go"
)

func main() {
    // Instantiates a client to use send messages to the segment API.
    client, err := analytics.NewWithConfig(
        os.Getenv("SEGMENT_WRITE_KEY"),
        analytics.Config{
            Endpoint: os.Getenv("SEGMENT_ENDPOINT"),
        },
    )
    if err != nil { // ALWAYS check for errors!
        panic(err)
    }

    // Enqueues a track event that will be sent asynchronously.
    client.Enqueue(analytics.Track{
        UserId: "test-user",
        Event:  "test-snippet",
    })

    // Flushes any queued messages and closes the client - DON'T forget this step.
    client.Close()
}

Reporting SDK metrics to DataDog

If you want to have SDK metrics (number of events succeeded, failed etc.) to be delivered to DataDog use the following example:

package main

import (
    "os"

    analytics "github.com/FindHotel/analytics-go"
)

func main() {
    // Instantiates a client to use send messages to the segment API.
    reporter := analytics.NewDatadogReporter(os.Getenv("DD_API_KEY"), os.Getenv("DD_APP_KEY"))
    // if you don't need metrics use
    // reporter := &analytics.DiscardReporter{}

    client, err := analytics.NewWithConfig(
        os.Getenv("SEGMENT_WRITE_KEY"),
        analytics.Config{
            Endpoint: os.Getenv("SEGMENT_ENDPOINT"),
            Reporters: []analytics.Reporter{reporter},
        },
    )
    if err != nil {
        panic(err)
    }

    // Enqueues a track event that will be sent asynchronously.
    client.Enqueue(analytics.Track{
        UserId: "test-user",
        Event:  "test-snippet",
    })

    // Flushes any queued messages and closes the client.
    client.Close()
}

License

The library is released under the MIT license.

Documentation

Index

Examples

Constants

View Source
const DefaultBatchSize = 250

DefaultBatchSize sets the default batch size used by client instances if none was explicitly set.

View Source
const DefaultEndpoint = "https://segment.fih.io"

DefaultEndpoint sets the default endpoint to which client instances send messages if none was explictly set.

View Source
const DefaultInterval = 5 * time.Second

DefaultInterval sets the default flush interval used by client instances if none was explicitly set.

View Source
const MB = 1024 * 1024

MB is the number of bytes in one megabyte.

View Source
const Version = "3.5.0"

Version of the client.

Variables

View Source
var (
	// This error is returned by methods of the `Client` interface when they are
	// called after the client was already closed.
	ErrClosed = errors.New("the client was already closed")

	// This error is used to notify the application that too many requests are
	// already being sent and no more messages can be accepted.
	ErrTooManyRequests = errors.New("too many requests are already in-flight")

	// This error is used to notify the client callbacks that a message send
	// failed because the JSON representation of a message exceeded the upper
	// limit.
	ErrMessageTooBig = errors.New("the message exceeds the maximum allowed size")
)

Functions

This section is empty.

Types

type Alias

type Alias struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string `json:"type,omitempty"`

	MessageId    string       `json:"messageId,omitempty"`
	PreviousId   string       `json:"previousId"`
	UserId       string       `json:"userId"`
	Timestamp    Time         `json:"timestamp,omitempty"`
	Context      *Context     `json:"context,omitempty"`
	Integrations Integrations `json:"integrations,omitempty"`
}

Alias represents object sent in a alias call as described in https://segment.com/docs/libraries/http/#alias

type AppInfo

type AppInfo struct {
	Name      string `json:"name,omitempty"`
	Version   string `json:"version,omitempty"`
	Build     string `json:"build,omitempty"`
	Namespace string `json:"namespace,omitempty"`
}

AppInfo provides the representation of the `context.app` object as defined in https://segment.com/docs/spec/common/#context

type Callback

type Callback interface {

	// This method is called for every message that was successfully sent to
	// the API.
	Success(Message)

	// This method is called for every message that failed to be sent to the
	// API and will be discarded by the client.
	Failure(Message, error)
}

Callback interface is used by analytics clients to notify the application when a message send succeeded or failed.

Callback methods are called by a client's internal goroutines, there are no guarantees on which goroutine will trigger the callbacks, the calls can be made sequentially or in parallel, the order doesn't depend on the order of messages were queued to the client.

Callback methods must return quickly and not cause long blocking operations to avoid interferring with the client's internal work flow.

type CampaignInfo

type CampaignInfo struct {
	Name    string `json:"name,omitempty"`
	Source  string `json:"source,omitempty"`
	Medium  string `json:"medium,omitempty"`
	Term    string `json:"term,omitempty"`
	Content string `json:"content,omitempty"`
}

CampaignInfo provides the representation of the `context.campaign` object as defined in https://segment.com/docs/spec/common/#context

type Client

type Client interface {
	io.Closer

	// Queues a message to be sent by the client when the conditions for a batch
	// upload are met.
	// This is the main method you'll be using, a typical flow would look like
	// this:
	//
	//	client := analytics.New(writeKey)
	//	...
	//	client.Enqueue(analytics.Track{ ... })
	//	...
	//	client.Close()
	//
	// The method returns an error if the message queue not be queued, which
	// happens if the client was already closed at the time the method was
	// called or if the message was malformed.
	Enqueue(Message) error
}

Client is the main API exposed by the analytics package. Values that satsify this interface are returned by the client constructors provided by the package and provide a way to send messages via the HTTP API.

func New

func New(writeKey string) Client

New instantiates a new client that uses the write key passed as first argument to send messages to the backend. The client is created with the default (empty) configuration.

func NewDiscardClient

func NewDiscardClient() Client

NewDiscardClient returns client which discards all messages.

func NewS3ClientWithConfig

func NewS3ClientWithConfig(config S3ClientConfig) (Client, error)

NewS3ClientWithConfig creates S3 client from provided configuration. Pass empty S3ClientConfig{} to use default config.

func NewWithConfig

func NewWithConfig(writeKey string, config Config) (Client, error)

NewWithConfig instantiates a new client that uses the write key and configuration passed as arguments to send messages to the backend. The function will return an error if the configuration contained impossible values (like a negative flush interval for example). When the function returns an error the returned client will always be nil.

type Config

type Config struct {

	// The endpoint to which the client connect and send their messages, set to
	// `DefaultEndpoint` by default.
	Endpoint string

	// The flushing interval of the client. Messages will be sent when they've
	// been queued up to the maximum batch size or when the flushing interval
	// timer triggers.
	Interval time.Duration

	// The HTTP transport used by the client, this allows an application to
	// redefine how requests are being sent at the HTTP level (for example,
	// to change the connection pooling policy).
	// If none is specified the client uses `http.DefaultTransport`.
	Transport http.RoundTripper

	// The logger used by the client to output info or error messages when that
	// are generated by background operations.
	// If none is specified the client uses a standard logger that outputs to
	// `os.Stderr`.
	Logger Logger

	// The callback object that will be used by the client to notify the
	// application when messages sends to the backend API succeeded or failed.
	Callback Callback

	// The maximum number of messages that will be sent in one API call.
	// Messages will be sent when they've been queued up to the maximum batch
	// size or when the flushing interval timer triggers.
	// Note that the API will still enforce a 500KB limit on each HTTP request
	// which is independent from the number of embedded messages.
	BatchSize int

	// When set to true the client will send more frequent and detailed messages
	// to its logger.
	Verbose bool

	// The default context set on each message sent by the client.
	DefaultContext *Context

	// The retry policy used by the client to resend requests that have failed.
	// The function is called with how many times the operation has been retried
	// and is expected to return how long the client should wait before trying
	// again.
	// If not set the client will fallback to use a default retry policy.
	RetryAfter func(int) time.Duration

	// Reporters are used to report metrics to external reporting system such
	// as DataDog. Useful implementations are DatadogReporter and LogReporter.
	Reporters []Reporter
	// contains filtered or unexported fields
}

Config instances carry the different configuration options that may be set when instantiating a client.

Each field's zero-value is either meaningful or interpreted as using the default value defined by the library.

type ConfigError

type ConfigError struct {

	// A human-readable message explaining why the configuration field's value
	// is invalid.
	Reason string

	// The name of the configuration field that was carrying an invalid value.
	Field string

	// The value of the configuration field that caused the error.
	Value interface{}
}

Returned by the `NewWithConfig` function when the one of the configuration fields was set to an impossible value (like a negative duration).

func (ConfigError) Error

func (e ConfigError) Error() string

type Context

type Context struct {
	App       AppInfo      `json:"app,omitempty"`
	Campaign  CampaignInfo `json:"campaign,omitempty"`
	Device    DeviceInfo   `json:"device,omitempty"`
	Library   LibraryInfo  `json:"library,omitempty"`
	Location  LocationInfo `json:"location,omitempty"`
	Network   NetworkInfo  `json:"network,omitempty"`
	OS        OSInfo       `json:"os,omitempty"`
	Page      PageInfo     `json:"page,omitempty"`
	Referrer  ReferrerInfo `json:"referrer,omitempty"`
	Screen    ScreenInfo   `json:"screen,omitempty"`
	IP        net.IP       `json:"ip,omitempty"`
	Locale    string       `json:"locale,omitempty"`
	Timezone  string       `json:"timezone,omitempty"`
	UserAgent string       `json:"userAgent,omitempty"`
	Traits    Traits       `json:"traits,omitempty"`

	// This map is used to allow extensions to the context specifications that
	// may not be documented or could be introduced in the future.
	// The fields of this map are inlined in the serialized context object,
	// there is no actual "extra" field in the JSON representation.
	Extra map[string]interface{} `json:"-"`
}

Context provides the representation of the `context` object as defined in https://segment.com/docs/spec/common/#context

func (Context) MarshalJSON

func (ctx Context) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the `json.Marshaler` interface. We have to flatten out the `Extra` field but the standard json package doesn't support it yet. Implementing this interface allows us to override the default marshaling of the context object and to the inlining ourselves.

Related discussion: https://github.com/golang/go/issues/6213

type DatadogReporter

type DatadogReporter struct {
	Client *datadog.Client

	*sync.Mutex
	// contains filtered or unexported fields
}

DatadogReporter reports metrics to DataDog.

func NewDatadogReporter

func NewDatadogReporter(apiKey, appKey string, tags ...string) *DatadogReporter

NewDatadogReporter is a factory method to create Datadog reporter with sane defaults.

func (*DatadogReporter) AddTags

func (dd *DatadogReporter) AddTags(tags ...string)

AddTags adds tags to be added to each metric reported.

func (*DatadogReporter) Flush

func (dd *DatadogReporter) Flush() error

Flush flushes reported metrics.

func (*DatadogReporter) Report

func (dd *DatadogReporter) Report(metricName string, value interface{}, tags []string, ts time.Time)

Report sends provided metric to Datadog.

func (*DatadogReporter) WithLogger

func (dd *DatadogReporter) WithLogger(logger Logger) *DatadogReporter

WithLogger sets logger to DatadogReporter.

type DeviceInfo

type DeviceInfo struct {
	Id            string `json:"id,omitempty"`
	Manufacturer  string `json:"manufacturer,omitempty"`
	Model         string `json:"model,omitempty"`
	Name          string `json:"name,omitempty"`
	Type          string `json:"type,omitempty"`
	Version       string `json:"version,omitempty"`
	AdvertisingID string `json:"advertisingId,omitempty"`
}

DeviceInfo provides the representation of the `context.device` object as defined in https://segment.com/docs/spec/common/#context

type DiscardLogger

type DiscardLogger struct{}

DiscardLogger discards all log messages supplied to it.

func (DiscardLogger) Errorf

func (l DiscardLogger) Errorf(format string, args ...interface{})

Errorf does nothing for DiscardLogger.

func (DiscardLogger) Logf

func (l DiscardLogger) Logf(format string, args ...interface{})

Logf does nothing for DiscardLogger.

type DiscardReporter

type DiscardReporter struct{}

DiscardReporter discards all metrics, useful for tests.

func (*DiscardReporter) AddTags

func (r *DiscardReporter) AddTags(tags ...string)

AddTags adds tags to be added to each metric reported.

func (*DiscardReporter) Flush

func (r *DiscardReporter) Flush() error

Flush flushes reported metrics.

func (DiscardReporter) Report

func (r DiscardReporter) Report(metricName string, value interface{}, tags []string, ts time.Time)

Report reports metrics.

type FieldError

type FieldError struct {

	// The human-readable representation of the type of structure that wasn't
	// initialized properly.
	Type string

	// The name of the field that wasn't properly initialized.
	Name string

	// The value of the field that wasn't properly initialized.
	Value interface{}
}

Instances of this type are used to represent errors returned when a field was no initialize properly in a structure passed as argument to one of the functions of this package.

func (FieldError) Error

func (e FieldError) Error() string

type Group

type Group struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string `json:"type,omitempty"`

	MessageId    string       `json:"messageId,omitempty"`
	AnonymousId  string       `json:"anonymousId,omitempty"`
	UserId       string       `json:"userId,omitempty"`
	GroupId      string       `json:"groupId"`
	Timestamp    Time         `json:"timestamp,omitempty"`
	Context      *Context     `json:"context,omitempty"`
	Traits       Traits       `json:"traits,omitempty"`
	Integrations Integrations `json:"integrations,omitempty"`
}

Group represents object sent in a group call as described in https://segment.com/docs/libraries/http/#group

type Identify

type Identify struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string `json:"type,omitempty"`

	MessageId    string       `json:"messageId,omitempty"`
	AnonymousId  string       `json:"anonymousId,omitempty"`
	UserId       string       `json:"userId,omitempty"`
	Timestamp    Time         `json:"timestamp,omitempty"`
	Context      *Context     `json:"context,omitempty"`
	Traits       Traits       `json:"traits,omitempty"`
	Integrations Integrations `json:"integrations,omitempty"`
}

This type represents object sent in an identify call as described in https://segment.com/docs/libraries/http/#identify

type Integrations

type Integrations map[string]interface{}

This type is used to represent integrations in messages that support it. It is a free-form where values are most often booleans that enable or disable integrations. Here's a quick example of how this type is meant to be used:

analytics.Track{
	UserId:       "0123456789",
	Integrations: analytics.NewIntegrations()
		.EnableAll()
		.Disable("Salesforce")
		.Disable("Marketo"),
}

The specifications can be found at https://segment.com/docs/spec/common/#integrations

func NewIntegrations

func NewIntegrations() Integrations

func (Integrations) Disable

func (i Integrations) Disable(name string) Integrations

func (Integrations) DisableAll

func (i Integrations) DisableAll() Integrations

func (Integrations) Enable

func (i Integrations) Enable(name string) Integrations

func (Integrations) EnableAll

func (i Integrations) EnableAll() Integrations

func (Integrations) Set

func (i Integrations) Set(name string, value interface{}) Integrations

Sets an integration named by the first argument to the specified value, any value other than `false` will be interpreted as enabling the integration.

type LibraryInfo

type LibraryInfo struct {
	Name    string `json:"name,omitempty"`
	Version string `json:"version,omitempty"`
}

LibraryInfo provides the representation of the `context.library` object as defined in https://segment.com/docs/spec/common/#context

type LocationInfo

type LocationInfo struct {
	City      string  `json:"city,omitempty"`
	Country   string  `json:"country,omitempty"`
	Region    string  `json:"region,omitempty"`
	Latitude  float64 `json:"latitude,omitempty"`
	Longitude float64 `json:"longitude,omitempty"`
	Speed     float64 `json:"speed,omitempty"`
}

LocationInfo provides the representation of the `context.location` object as defined in https://segment.com/docs/spec/common/#context

type LogReporter

type LogReporter struct {
	// contains filtered or unexported fields
}

LogReporter report metrics as a log.

func NewLogReporter

func NewLogReporter(l ...Logger) *LogReporter

NewLogReporter returns new log repoter ready to use.

func (*LogReporter) AddTags

func (r *LogReporter) AddTags(tags ...string)

AddTags adds tags to be added to each metric reported.

func (*LogReporter) Flush

func (r *LogReporter) Flush() error

Flush flushes reported metrics.

func (LogReporter) Report

func (r LogReporter) Report(metricName string, value interface{}, tags []string, ts time.Time)

Report reports metrics.

type Logger

type Logger interface {

	// Analytics clients call this method to log regular messages about the
	// operations they perform.
	// Messages logged by this method are usually tagged with an `INFO` log
	// level in common logging libraries.
	Logf(format string, args ...interface{})

	// Analytics clients call this method to log errors they encounter while
	// sending events to the backend servers.
	// Messages logged by this method are usually tagged with an `ERROR` log
	// level in common logging libraries.
	Errorf(format string, args ...interface{})
}

Logger can be used to define where the analytics client logs are written.

func StdLogger

func StdLogger(logger *log.Logger) Logger

StdLogger instantiate an object that statisfies the analytics.Logger interface and send logs to standard logger passed as argument.

type Message

type Message interface {
	// contains filtered or unexported methods
}

Message interface is used to represent analytics objects that can be sent via a client.

Types like analytics.Track, analytics.Page, etc... implement this interface and therefore can be passed to the analytics.Client.Send method.

type NetworkInfo

type NetworkInfo struct {
	Bluetooth bool   `json:"bluetooth,omitempty"`
	Cellular  bool   `json:"cellular,omitempty"`
	WIFI      bool   `json:"wifi,omitempty"`
	Carrier   string `json:"carrier,omitempty"`
}

NetworkInfo provides the representation of the `context.network` object as defined in https://segment.com/docs/spec/common/#context

type OSInfo

type OSInfo struct {
	Name    string `json:"name,omitempty"`
	Version string `json:"version,omitempty"`
}

OSInfo provides the representation of the `context.os` object as defined in https://segment.com/docs/spec/common/#context

type Page

type Page struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string `json:"type,omitempty"`

	MessageId    string       `json:"messageId,omitempty"`
	AnonymousId  string       `json:"anonymousId,omitempty"`
	UserId       string       `json:"userId,omitempty"`
	Name         string       `json:"name,omitempty"`
	Timestamp    Time         `json:"timestamp,omitempty"`
	Context      *Context     `json:"context,omitempty"`
	Properties   Properties   `json:"properties,omitempty"`
	Integrations Integrations `json:"integrations,omitempty"`
}

Page represents object sent in a page call as described in https://segment.com/docs/libraries/http/#page

type PageInfo

type PageInfo struct {
	Hash     string `json:"hash,omitempty"`
	Path     string `json:"path,omitempty"`
	Referrer string `json:"referrer,omitempty"`
	Search   string `json:"search,omitempty"`
	Title    string `json:"title,omitempty"`
	URL      string `json:"url,omitempty"`
}

PageInfo provides the representation of the `context.page` object as defined in https://segment.com/docs/spec/common/#context

type Product

type Product struct {
	ID    string  `json:"id,omitempty"`
	SKU   string  `json:"sky,omitempty"`
	Name  string  `json:"name,omitempty"`
	Price float64 `json:"price"`
}

Product represents products in the E-commerce API.

type Properties

type Properties map[string]interface{}

Properties represent properties in messages that support it. It is a free-form object so the application can set any value it sees fit but a few helper method are defined to make it easier to instantiate properties with common fields. Here's a quick example of how this type is meant to be used:

analytics.Page{
	UserId: "0123456789",
	Properties: analytics.NewProperties()
		.SetRevenue(10.0)
		.SetCurrency("USD"),
}

func NewProperties

func NewProperties() Properties

NewProperties creates new Properties map.

func (Properties) Set

func (p Properties) Set(name string, value interface{}) Properties

func (Properties) SetCategory

func (p Properties) SetCategory(category string) Properties

func (Properties) SetCoupon

func (p Properties) SetCoupon(coupon string) Properties

func (Properties) SetCurrency

func (p Properties) SetCurrency(currency string) Properties

func (Properties) SetDiscount

func (p Properties) SetDiscount(discount float64) Properties

func (Properties) SetName

func (p Properties) SetName(name string) Properties

func (Properties) SetOrderId

func (p Properties) SetOrderId(id string) Properties

func (Properties) SetPath

func (p Properties) SetPath(path string) Properties

func (Properties) SetPrice

func (p Properties) SetPrice(price float64) Properties

func (Properties) SetProductId

func (p Properties) SetProductId(id string) Properties

func (Properties) SetProducts

func (p Properties) SetProducts(products ...Product) Properties

func (Properties) SetReferrer

func (p Properties) SetReferrer(referrer string) Properties

func (Properties) SetRepeat

func (p Properties) SetRepeat(repeat bool) Properties

func (Properties) SetRevenue

func (p Properties) SetRevenue(revenue float64) Properties

func (Properties) SetSKU

func (p Properties) SetSKU(sku string) Properties

func (Properties) SetShipping

func (p Properties) SetShipping(shipping float64) Properties

func (Properties) SetSubtotal

func (p Properties) SetSubtotal(subtotal float64) Properties

func (Properties) SetTax

func (p Properties) SetTax(tax float64) Properties

func (Properties) SetTitle

func (p Properties) SetTitle(title string) Properties

func (Properties) SetTotal

func (p Properties) SetTotal(total float64) Properties

func (Properties) SetURL

func (p Properties) SetURL(url string) Properties

func (Properties) SetValue

func (p Properties) SetValue(value float64) Properties

type ReferrerInfo

type ReferrerInfo struct {
	Type string `json:"type,omitempty"`
	Name string `json:"name,omitempty"`
	URL  string `json:"url,omitempty"`
	Link string `json:"link,omitempty"`
}

ReferrerInfo provides the representation of the `context.referrer` object as defined in https://segment.com/docs/spec/common/#context

type Reporter

type Reporter interface {
	Report(metricName string, value interface{}, tags []string, ts time.Time)
	Flush() error
	AddTags(tags ...string)
}

Reporter provides a function to reporting metrics.

type S3

type S3 struct {
	Bucket string
	Stage  string

	// Stream is an arbitrary name of the stream where messages will be delivered.
	// Examples: tuna, salmon, haring, etc. Each system receives its own stream.
	Stream string

	MaxBatchBytes int

	KeyConstructor func(now func() Time, uid func() string) string

	UploaderOptions []func(*s3manager.Uploader)
}

S3 is a configuration for s3Client.

type S3ClientConfig

type S3ClientConfig struct {
	Config
	S3 S3
}

S3ClientConfig provides configuration for S3 Client.

type Screen

type Screen struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string `json:"type,omitempty"`

	MessageId    string       `json:"messageId,omitempty"`
	AnonymousId  string       `json:"anonymousId,omitempty"`
	UserId       string       `json:"userId,omitempty"`
	Name         string       `json:"name,omitempty"`
	Timestamp    Time         `json:"timestamp,omitempty"`
	Context      *Context     `json:"context,omitempty"`
	Properties   Properties   `json:"properties,omitempty"`
	Integrations Integrations `json:"integrations,omitempty"`
}

Screen represents object sent in a screen call as described in https://segment.com/docs/libraries/http/#screen

type ScreenInfo

type ScreenInfo struct {
	Density int `json:"density,omitempty"`
	Width   int `json:"width,omitempty"`
	Height  int `json:"height,omitempty"`
}

ScreenInfo provides the representation of the `context.screen` object as defined in https://segment.com/docs/spec/common/#context

type Time

type Time time.Time

Time is a wrapper over time.Time with custom json marshalling.

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON marshals time as unix milliseconds.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals milliseconds into Time.

type Track

type Track struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string `json:"type,omitempty"`

	MessageId    string       `json:"messageId,omitempty"`
	AnonymousId  string       `json:"anonymousId,omitempty"`
	UserId       string       `json:"userId,omitempty"`
	Event        string       `json:"event"`
	Timestamp    Time         `json:"timestamp,omitempty"`
	Context      *Context     `json:"context,omitempty"`
	Properties   Properties   `json:"properties,omitempty"`
	Integrations Integrations `json:"integrations,omitempty"`
}

Track represents object sent in a track call as described in https://segment.com/docs/libraries/http/#track

Example
body, server := mockServer()
defer server.Close()

client, _ := NewWithConfig("h97jamjwbh", Config{
	Endpoint:  server.URL,
	BatchSize: 1,
	now:       mockTime,
	uid:       mockId,
})
defer client.Close()

client.Enqueue(Track{
	Event:  "Download",
	UserId: "123456",
	Properties: Properties{
		"application": "Segment Desktop",
		"version":     "1.1.0",
		"platform":    "osx",
	},
})

s := strings.Replace(string(<-body),
	fmt.Sprintf(`"version": "%s"`, Version),
	`"version": "3.4.0"`,
	-1,
)

fmt.Printf("%s\n", s)
Output:

{
  "batch": [
    {
      "event": "Download",
      "messageId": "I'm unique",
      "properties": {
        "application": "Segment Desktop",
        "platform": "osx",
        "version": "1.1.0"
      },
      "timestamp": 1257894000000,
      "type": "track",
      "userId": "123456"
    }
  ],
  "context": {
    "library": {
      "name": "analytics-go",
      "version": "3.4.0"
    }
  },
  "messageId": "I'm unique",
  "sentAt": 1257894000000
}

type Traits

type Traits map[string]interface{}

Traits is used to represent traits in messages that support it. It is a free-form object so the application can set any value it sees fit but a few helper method are defined to make it easier to instantiate traits with common fields. Here's a quick example of how this type is meant to be used:

analytics.Identify{
	UserId: "0123456789",
	Traits: analytics.NewTraits()
		.SetFirstName("Luke")
		.SetLastName("Skywalker")
		.Set("Role", "Jedi"),
}

The specifications can be found at https://segment.com/docs/spec/identify/#traits

func NewTraits

func NewTraits() Traits

func (Traits) Set

func (t Traits) Set(field string, value interface{}) Traits

func (Traits) SetAddress

func (t Traits) SetAddress(address string) Traits

func (Traits) SetAge

func (t Traits) SetAge(age int) Traits

func (Traits) SetAvatar

func (t Traits) SetAvatar(url string) Traits

func (Traits) SetBirthday

func (t Traits) SetBirthday(date time.Time) Traits

func (Traits) SetCreatedAt

func (t Traits) SetCreatedAt(date time.Time) Traits

func (Traits) SetDescription

func (t Traits) SetDescription(desc string) Traits

func (Traits) SetEmail

func (t Traits) SetEmail(email string) Traits

func (Traits) SetFirstName

func (t Traits) SetFirstName(firstName string) Traits

func (Traits) SetGender

func (t Traits) SetGender(gender string) Traits

func (Traits) SetLastName

func (t Traits) SetLastName(lastName string) Traits

func (Traits) SetName

func (t Traits) SetName(name string) Traits

func (Traits) SetPhone

func (t Traits) SetPhone(phone string) Traits

func (Traits) SetTitle

func (t Traits) SetTitle(title string) Traits

func (Traits) SetUsername

func (t Traits) SetUsername(username string) Traits

func (Traits) SetWebsite

func (t Traits) SetWebsite(url string) Traits

Directories

Path Synopsis
cmd
cli

Jump to

Keyboard shortcuts

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