taplink

package module
v0.0.0-...-7a636c4 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2017 License: MIT Imports: 17 Imported by: 1

README

Build Status codecov Go Report Card

Usage

Basic usage is as follows:

import (
    "log"

    "github.com/TapLink/go-taplink"
)

func main() {

    api := taplink.New("my-api-key")
    pwd, err := api.NewPassword([]byte("my-password-hash"))
    if err != nil {
        log.Println("NewPassword error", err)
        return
    }

    verify, err := api.VerifyPassword([]byte("my-password-hash"), pwd.Hash, pwd.VersionID)
    if err != nil {
        log.Println("VerifyPassword error", err)
        return
    }

    log.Println("Did it match?", verify.Matched)
}

You can also set parameters related to HTTP requests, and also enable/disable tracking of statistics:

package examples

import (
	"log"
	"time"

	"github.com/TapLink/taplink-go"
)

func main() {

	// You can update the RetryLimit and RetryDelay for failed HTTP requests, too.
	// The API client will adhere to these settings.
	taplink.RetryLimit = 10
	taplink.RetryDelay = 30 * time.Second

	api := taplink.New("my-api-key")

	// To enable the collection of stats for the API client, use Stats().Enable()
	// By default the stats are disabled.
	api.Stats().Enable()
	api.VerifyPassword([]byte("my-password-hash"), []byte("expected"), 0)

	// If you want to load config from the TapLink api and use servers other than the the taplink.DefaultHost, then load config
	if err := api.Config().Load(); err != nil {
		log.Println("couldn't load config", err)
	}

	// After loading config, you can access the list of servers the client can connect to with Config().Servers
	log.Println("using servers", api.Config().Servers())

	// To get the stats, use these funcs...
	log.Println("total number of requests made", api.Stats().Get(taplink.DefaultHost).Requests())
	log.Println("history of latency for each successful request", api.Stats().Get(taplink.DefaultHost).Latency())
	log.Println("average time of requests", api.Stats().Get(taplink.DefaultHost).Latency().Avg())
	log.Println("num requests which had errors", api.Stats().Get(taplink.DefaultHost).Errors())

	// To disable the collection of stats, use DisableStats()
	api.Stats().Disable()
}

If you're using on App Engine, then you'll need to set the HTTPClient with a valid App Engine compatible HTTP client. You'll have to do this for every request. You can do this in two ways:

import (
    "net/http"

    "google.golang.org/appengine"

    "github.com/TapLink/taplink-go"
)

func myHandler(w http.ResponseWriter, r *http.Request) {

    ctx := appengine.NewContext(r)

    // First option, set the context with UseContext(). Note that this function
    // is not available for code which is not running in App Engine, and won't
    // compile outside the App Engine environment.
    taplink.UseContext(ctx)

    // Second option, set the HTTPClient directly. This would allow further
    // customization of the client if needed.
    client := urlfetch.New(ctx)
    taplink.HTTPClient = client

    // Now do something with the Taplink library, as in previous examples...
}

Documentation

Index

Constants

View Source
const (
	HostSelectRandom     = iota
	HostSelectRoundRobin = iota
)

Host selection algorithms

Variables

View Source
var (

	// DefaultTimeout is the default HTTP request timeout
	DefaultTimeout = 30 * time.Second
	// DefaultKeepAlive is the default HTTP keep-alive duration
	DefaultKeepAlive = 30 * time.Second

	// RetryLimit indicates how many times a connection should be retried before failing
	RetryLimit = 3
	// RetryDelay is the duration to wait between retry attempts
	RetryDelay = 1 * time.Second

	// ErrHostNotFound is returned if the given host does not exist
	ErrHostNotFound = errors.New("host not found")
)
View Source
var (

	// DefaultHost is the default API host
	DefaultHost = "api.taplink.co"
)
View Source
var (

	// HTTPClient defines the HTTP client used for HTTP connections
	HTTPClient = &http.Client{
		Timeout: DefaultTimeout,
		Transport: &http.Transport{
			Dial: (&net.Dialer{
				Timeout:   DefaultTimeout,
				KeepAlive: DefaultKeepAlive,
			}).Dial,
		},
	}
)

Functions

This section is empty.

Types

type API

type API interface {

	// Config
	Config() Configuration

	// API funcs
	VerifyPassword(hash []byte, expectedHash []byte, versionID int64) (*VerifyPassword, error)
	NewPassword(hash []byte) (*NewPassword, error)

	// Stats returns stats about each host the client has connected to
	Stats() Statistics
}

API is an interface which exposes TapLink API functionality

func New

func New(appID string) API

New returns a new TapLink API connection

type Client

type Client struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Client is a struct which implements the API interface

func (*Client) Config

func (c *Client) Config() Configuration

Config returns the current client configuration

func (*Client) NewPassword

func (c *Client) NewPassword(hash1 []byte) (*NewPassword, error)

NewPassword calculates 'salt1' and 'hash2' for a new password, using the latest data pool settings. Also returns 'versionId' for the current settings, in case data pool settings are updated in the future Inputs:

'hash1Hex' - hash of the user's password, as a hex string
'callback' - function(err, hash2Hex, versionId)
    o err       : 'err' from request, or null if request succeeded
    o hash2Hex  : value of 'hash2' as a hex string
    o versionId : version id of the current data pool settings used for this request

func (*Client) Stats

func (c *Client) Stats() Statistics

Stats returns stats about connections to the server

func (*Client) VerifyPassword

func (c *Client) VerifyPassword(hash []byte, expected []byte, versionID int64) (*VerifyPassword, error)

VerifyPassword verifies a password for an existing user which was stored using blind hashing. 'hash' - hash of the user's password 'expected' - expected value of hash2 'versionId' - version identifier for data pool settings to use If a new 'versionId' and 'hash2' value are returned, they can either be ignored, or both must be updated in the data store together which will cause the latest data pool settings to be used when blind hashing for this user in the future. If the versionID is 0, the default version will be used

type Config

type Config struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Config defines basic configuration for connecting to the API

func (*Config) AppID

func (c *Config) AppID() string

AppID returns the app ID

func (*Config) Headers

func (c *Config) Headers() map[string]string

Headers returns the headers to be added to each request

func (*Config) Host

func (c *Config) Host(attempts int) string

Host returns the API server to connect to based on the available servers and the host selection algorithm

func (*Config) LastModified

func (c *Config) LastModified() time.Time

LastModified returns the last modification of the TapLink configuration

func (*Config) Load

func (c *Config) Load() error

Load gets the configuration options from the API for the given app ID.

func (*Config) Servers

func (c *Config) Servers() []string

Servers returns the API servers available to connect to

func (*Config) Stats

func (c *Config) Stats() Statistics

Stats returns a statistics interface for enabling/disabling/managing statistics.

type Configuration

type Configuration interface {
	AppID() string
	Host(attempts int) string
	Headers() map[string]string
	LastModified() time.Time
	Servers() []string
	Load() error

	Stats() Statistics
}

Configuration defines an interface which provides configuration info for requests to the API

type Errors

type Errors map[int]int

Errors is a map of how error codes (key) and count of those codes (value)

func (Errors) Count

func (e Errors) Count(code int) int

Count returns the number of errors for the given code.

func (Errors) Len

func (e Errors) Len() (l int)

Len returns the total number of errors

type HostStats

type HostStats interface {
	Errors() Errors
	Requests() int
	Timeouts() int
	Latency() Latency
	ErrorRate() float64
	Last(time.Duration) HostStats
}

HostStats defines an interface which provides detailed information about the statistics related to connections to the given host.

type Latency

type Latency []time.Duration

Latency is a slice of duration of the requests.

func (Latency) Avg

func (l Latency) Avg() time.Duration

Avg returns the average latency for the slice

func (Latency) Len

func (l Latency) Len() int

Len returns the length of the underlying slice

type NewPassword

type NewPassword struct {
	Hash      []byte
	VersionID int64
}

NewPassword returns a new password hash and the version it was created with

func (NewPassword) String

func (p NewPassword) String() string

String returns the hex-encoded value of the password hash

type Options

type Options struct {
	LastModified int64    `json:"lastModified"`
	Servers      []string `json:"servers"`
}

Options is the options API response

type Salt

type Salt struct {
	Salt []byte
	// VersionID is the version ID used in the request
	VersionID int64 `json:"-"`
	// NewVersionID is the new version ID to use, if any.
	NewVersionID int64 `json:"vid"`
	// NewSalt is the new salt to use if newer data pool settings are available
	NewSalt []byte `json:"-"`
}

Salt contains a salt for the current version, and NewSalt if a new version is available

func (Salt) String

func (s Salt) String() string

type Statistics

type Statistics interface {
	Enable()
	Disable()
	AddSuccess(host string, latency time.Duration)
	AddError(host string, code int)
	AddTimeout(host string)
	Get(host string) HostStats
	SetServers(servers []string)
	Hosts() []string
}

Statistics defines an interface for getting and setting connection statistics

type VerifyPassword

type VerifyPassword struct {
	Matched      bool
	VersionID    int64
	NewVersionID int64
	Hash         []byte
	NewHash      []byte
}

VerifyPassword provides information about whether a password matched and related hashes

func (VerifyPassword) String

func (v VerifyPassword) String() string

String returns the hex-encoded value of the password hash

type Version

type Version int64

Version is a version number for the TapLink API

func (Version) String

func (v Version) String() string

String implements fmt.Stringer interface. If the version is empty, the API expects "" so this return it that way

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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