analytics-go.v3: gopkg.in/segmentio/analytics-go.v3 Index | Examples | Files | Directories

package analytics

import "gopkg.in/segmentio/analytics-go.v3"

Index

Examples

Package Files

alias.go analytics.go config.go context.go error.go executor.go group.go identify.go integrations.go json.go logger.go message.go page.go properties.go screen.go timeout_16.go track.go traits.go

Constants

const DefaultBatchSize = 250

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

const DefaultEndpoint = "https://api.segment.io"

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

const DefaultInterval = 5 * time.Second

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

const Version = "3.0.0"

Version of the client.

Variables

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")
)

type Alias Uses

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.Time    `json:"timestamp,omitempty"`
    Context      *Context     `json:"context,omitempty"`
    Integrations Integrations `json:"integrations,omitempty"`
}

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

func (Alias) Validate Uses

func (msg Alias) Validate() error

type AppInfo Uses

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

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

type Callback Uses

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)
}

Values implementing this interface are 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 Uses

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

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

type Client Uses

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
}

This interface 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 Uses

func New(writeKey string) Client

Instantiate 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 configuration.

func NewWithConfig Uses

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

Instantiate 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 Uses

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
    // contains filtered or unexported fields
}

Instances of this type 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 Uses

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 Uses

func (e ConfigError) Error() string

type Context Uses

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

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

func (Context) MarshalJSON Uses

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

Satisfy 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 DeviceInfo Uses

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

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

type FieldError Uses

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 Uses

func (e FieldError) Error() string

type Group Uses

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.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 a group call as described in https://segment.com/docs/libraries/http/#group

func (Group) Validate Uses

func (msg Group) Validate() error

type Identify Uses

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

func (Identify) Validate Uses

func (msg Identify) Validate() error

type Integrations Uses

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 Uses

func NewIntegrations() Integrations

func (Integrations) Disable Uses

func (i Integrations) Disable(name string) Integrations

func (Integrations) DisableAll Uses

func (i Integrations) DisableAll() Integrations

func (Integrations) Enable Uses

func (i Integrations) Enable(name string) Integrations

func (Integrations) EnableAll Uses

func (i Integrations) EnableAll() Integrations

func (Integrations) Set Uses

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 Uses

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

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

type LocationInfo Uses

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

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

type Logger Uses

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{})
}

Instances of types implementing this interface can be used to define where the analytics client logs are written.

func StdLogger Uses

func StdLogger(logger *log.Logger) Logger

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

type Message Uses

type Message interface {

    // Validate validates the internal structure of the message, the method must return
    // nil if the message is valid, or an error describing what went wrong.
    Validate() error
    // contains filtered or unexported methods
}

This 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 Uses

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

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

type OSInfo Uses

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

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

type Page Uses

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.Time    `json:"timestamp,omitempty"`
    Context      *Context     `json:"context,omitempty"`
    Properties   Properties   `json:"properties,omitempty"`
    Integrations Integrations `json:"integrations,omitempty"`
}

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

func (Page) Validate Uses

func (msg Page) Validate() error

type PageInfo Uses

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

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

type Product Uses

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

This type represents products in the E-commerce API.

type Properties Uses

type Properties map[string]interface{}

This type is used to 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 Uses

func NewProperties() Properties

func (Properties) Set Uses

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

func (Properties) SetCategory Uses

func (p Properties) SetCategory(category string) Properties

func (Properties) SetCoupon Uses

func (p Properties) SetCoupon(coupon string) Properties

func (Properties) SetCurrency Uses

func (p Properties) SetCurrency(currency string) Properties

func (Properties) SetDiscount Uses

func (p Properties) SetDiscount(discount float64) Properties

func (Properties) SetName Uses

func (p Properties) SetName(name string) Properties

func (Properties) SetOrderId Uses

func (p Properties) SetOrderId(id string) Properties

func (Properties) SetPath Uses

func (p Properties) SetPath(path string) Properties

func (Properties) SetPrice Uses

func (p Properties) SetPrice(price float64) Properties

func (Properties) SetProductId Uses

func (p Properties) SetProductId(id string) Properties

func (Properties) SetProducts Uses

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

func (Properties) SetReferrer Uses

func (p Properties) SetReferrer(referrer string) Properties

func (Properties) SetRepeat Uses

func (p Properties) SetRepeat(repeat bool) Properties

func (Properties) SetRevenue Uses

func (p Properties) SetRevenue(revenue float64) Properties

func (Properties) SetSKU Uses

func (p Properties) SetSKU(sku string) Properties

func (Properties) SetShipping Uses

func (p Properties) SetShipping(shipping float64) Properties

func (Properties) SetSubtotal Uses

func (p Properties) SetSubtotal(subtotal float64) Properties

func (Properties) SetTax Uses

func (p Properties) SetTax(tax float64) Properties

func (Properties) SetTitle Uses

func (p Properties) SetTitle(title string) Properties

func (Properties) SetTotal Uses

func (p Properties) SetTotal(total float64) Properties

func (Properties) SetURL Uses

func (p Properties) SetURL(url string) Properties

func (Properties) SetValue Uses

func (p Properties) SetValue(value float64) Properties

type ReferrerInfo Uses

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

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

type Screen Uses

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.Time    `json:"timestamp,omitempty"`
    Context      *Context     `json:"context,omitempty"`
    Properties   Properties   `json:"properties,omitempty"`
    Integrations Integrations `json:"integrations,omitempty"`
}

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

func (Screen) Validate Uses

func (msg Screen) Validate() error

type ScreenInfo Uses

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

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

type Track Uses

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.Time    `json:"timestamp,omitempty"`
    Context      *Context     `json:"context,omitempty"`
    Properties   Properties   `json:"properties,omitempty"`
    Integrations Integrations `json:"integrations,omitempty"`
}

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

Code:

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",
    },
})

fmt.Printf("%s\n", <-body)

Output:

{
  "batch": [
    {
      "event": "Download",
      "messageId": "I'm unique",
      "properties": {
        "application": "Segment Desktop",
        "platform": "osx",
        "version": "1.1.0"
      },
      "timestamp": "2009-11-10T23:00:00Z",
      "type": "track",
      "userId": "123456"
    }
  ],
  "context": {
    "library": {
      "name": "analytics-go",
      "version": "3.0.0"
    }
  },
  "messageId": "I'm unique",
  "sentAt": "2009-11-10T23:00:00Z"
}

func (Track) Validate Uses

func (msg Track) Validate() error

type Traits Uses

type Traits map[string]interface{}

This type 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 Uses

func NewTraits() Traits

func (Traits) Set Uses

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

func (Traits) SetAddress Uses

func (t Traits) SetAddress(address string) Traits

func (Traits) SetAge Uses

func (t Traits) SetAge(age int) Traits

func (Traits) SetAvatar Uses

func (t Traits) SetAvatar(url string) Traits

func (Traits) SetBirthday Uses

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

func (Traits) SetCreatedAt Uses

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

func (Traits) SetDescription Uses

func (t Traits) SetDescription(desc string) Traits

func (Traits) SetEmail Uses

func (t Traits) SetEmail(email string) Traits

func (Traits) SetFirstName Uses

func (t Traits) SetFirstName(firstName string) Traits

func (Traits) SetGender Uses

func (t Traits) SetGender(gender string) Traits

func (Traits) SetLastName Uses

func (t Traits) SetLastName(lastName string) Traits

func (Traits) SetName Uses

func (t Traits) SetName(name string) Traits

func (Traits) SetPhone Uses

func (t Traits) SetPhone(phone string) Traits

func (Traits) SetTitle Uses

func (t Traits) SetTitle(title string) Traits

func (Traits) SetUsername Uses

func (t Traits) SetUsername(username string) Traits

func (Traits) SetWebsite Uses

func (t Traits) SetWebsite(url string) Traits

Directories

PathSynopsis
examples

Package analytics imports 16 packages (graph) and is imported by 8 packages. Updated 2019-09-21. Refresh now. Tools for package owners.