lyft

package module
v0.0.0-...-e9ebf91 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2018 License: BSD-3-Clause Imports: 13 Imported by: 1

README

lyft-go

Package lyft implements a Go client for v1 of lyft.com's HTTP API.

No API guarantees yet, so please vendor. Particularly don't depend on the JSON encoding/decoding of types.

go get github.com/nishanths/lyft-go/...

Docs

GoDoc

See the Usage section for a usage example.

License

BSD 3-Clause. See the LICENSE file at the root of the repository.

Documentation

Overview

Package lyft provides a client for Lyft's v1 HTTP API. Along with its subpackages, it supports authentication, webhooks, Lyft's debug headers, and most endpoints. Lyft's API reference is available at https://developer.lyft.com/v1/docs/overview.

Errors

When the HTTP roundtrip succeeds but there was an application-level error, the error from will be of type *StatusError (and sometimes, another more specific type documented per-method). The error can be inspected for more details on what went wrong.

Response Header and Request-ID

Methods on the client typically have a signature like:

func (c *Client) Foo() (T, http.Header, error)

The returned header is the the HTTP response header. It is safe to access when the error is nil, of type *StatusError, or of a documented concrete error type.

The returned header is useful for obtaining the rate limit header and the unique Request-ID header set by Lyft. For details, see https://developer.lyft.com/v1/docs/errors#section-detailed-information-on-error-codes.

Miscellaneous formats

According to http://petstore.swagger.io/?url=https://api.lyft.com/v1/spec#/, the format of the currency strings returned is ISO 4217.

Usage

This example shows how to obtain an access token and find the ride types available at a location.

// Obtain an access token using the two-legged or three-legged flows.
t, err := twoleg.GenerateToken(http.DefaultClient, lyft.BaseURL, os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET"))
if err != nil {
    log.Fatalf("error generating token: %s", err)
}

// Create a client.
c := lyft.NewClient(t.AccessToken)

// Make requests.
r, header, err := c.RideTypes(37.7, -122.2)
if err != nil {
    log.Fatalf("error getting ride types: %s", err)
}
fmt.Printf("ride types: %+v\n", r)
fmt.Printf("Request-ID: %s\n", lyft.RequestID(header))

Missing Features

The package does not yet support the sandbox-specific routes and the ride rating route.

Index

Constants

View Source
const (
	InvalidToken         = "invalid_token"
	TokenExpired         = "token_expired"
	InsufficientScope    = "insufficient_scope"
	UnsupportedGrantType = "unsupported_grant_type"
)

Possible values for the Reason field in StatusError.

View Source
const (
	RideTypeLyft    = "lyft"
	RideTypePlus    = "lyft_plus"
	RideTypeLine    = "lyft_line"
	RideTypePremier = "lyft_premier"
	RideTypeLux     = "lyft_lux"
	RideTypeLuxSUV  = "lyft_luxsuv"
)

Ride types. May not be an exhaustive list.

View Source
const (
	StatusPending    = "pending"
	StatusAccepted   = "accepted"
	StatusArrived    = "arrived"
	StatusPickedUp   = "pickedUp"
	StatusDroppedOff = "droppedOff"
	StatusCanceled   = "canceled"
	StatusUnknown    = "unknown"
)

Ride statuses.

View Source
const (
	ProfileBusiness = "business"
	ProfilePersonal = "personal"
)

Ride profiles.

View Source
const BaseURL = "https://api.lyft.com"

BaseURL is the base URL for Lyft's HTTP API.

View Source
const IgnoreArg float64 = -181 // so that valid longitudes aren't ignored.

IgnoreArg is a sentinel value that can be used when calling a function that has an optional float64 argument.

View Source
const TimeLayout = time.RFC3339

Variables

This section is empty.

Functions

func IsRateLimit

func IsRateLimit(err error) bool

IsRateLimit returns whether the error arose because of running into a rate limit.

func IsTokenExpired

func IsTokenExpired(err error) bool

IsTokenExpired returns true if the error arose because the access token expired.

func RateLimit

func RateLimit(h http.Header) (n int, ok bool)

RateLimit returns the value of X-Ratelimit-Limit.

func RateRemaining

func RateRemaining(h http.Header) (n int, ok bool)

RateRemaining returns the value of X-Ratelimit-Remaining.

func RequestID

func RequestID(h http.Header) string

RequestID gets the value of the Request-ID key from a response header.

func RideStatusDisplay

func RideStatusDisplay(s string) string

func RideTypeDisplay

func RideTypeDisplay(r string) string

RideTypeDisplay returns a nice display string for the supplied ride type.

Types

type CancelRideError

type CancelRideError struct {
	ErrorInfo
	Amount        float64
	Currency      string
	Token         string
	TokenDuration time.Duration
}

func (*CancelRideError) Error

func (c *CancelRideError) Error() string

type CancellationPrice

type CancellationPrice struct {
	Amount        int
	Currency      string
	Token         string
	TokenDuration time.Duration
}

type Charge

type Charge struct {
	Amount        int    `json:"amount"`
	Currency      string `json:"currency"`
	PaymentMethod string `json:"payment_method"`
}

type Client

type Client struct {
	// The following fields are optional.
	HTTPClient *http.Client // Uses http.DefaultClient if nil.
	Header     http.Header  // Extra request headers to add.
	BaseURL    string       // The base URL of the API; uses the package-level BaseURL if empty. Useful in tests.
	// contains filtered or unexported fields
}

Client is a client for the Lyft API. Use NewClient to create a client. Methods on a client are goroutine safe, unless the client's fields are being modified directly by other goroutines.

func NewClient

func NewClient(accessToken string) *Client

func (*Client) AccessToken

func (c *Client) AccessToken() string

func (*Client) CancelRide

func (c *Client) CancelRide(rideID, cancelToken string) (http.Header, error)

CancelRide cancels the specificed ride. cancelToken is the cancel confirmation token; it is optional. See https://developer.lyft.com/reference#ride-request-cancel for more details on the token.

If more action is required to cancel the ride, a returned error of type *CancelRideError will have more details.

func (*Client) CostEstimates

func (c *Client) CostEstimates(startLat, startLng, endLat, endLng float64, rideType string) ([]CostEstimate, http.Header, error)

CostEstimates returns the estimated cost, distance, and duration of a ride. The end locations are optional and are ignored if the value equals the package-level const IgnoreArg. rideType is also optional; if it is set, estimates will be returned for the specified type only.

func (*Client) DriverETA

func (c *Client) DriverETA(startLat, startLng, endLat, endLng float64, rideType string) ([]ETAEstimate, http.Header, error)

DriverETA estimates the time for the nearest driver to reach the specifed location. The end locations are optional and are ignored if the value equals the package-level const IgnoreArg. The rideType argument is also optional. If set, estimates will be returned for the specified type only.

func (*Client) DriversNearby

func (c *Client) DriversNearby(lat, lng float64) ([]NearbyDriver, http.Header, error)

DriversNearby returns the location of drivers near a location.

func (*Client) RequestRide

func (c *Client) RequestRide(req RideRequest) (CreatedRide, http.Header, error)

RequestRide requests a ride for a user. As of 2017-11-05, Lyft Line is not fully supported. See https://developer.lyft.com/reference#ride-request for details.

If further action (such as confirming the cost) is required before the ride can be successfully created, the error will be of type *RideRequestError. This corresponds to the 400 status code documented in Lyft's API reference.

func (*Client) RideDetail

func (c *Client) RideDetail(rideID string) (RideDetail, http.Header, error)

func (*Client) RideHistory

func (c *Client) RideHistory(start, end time.Time, limit int32) ([]RideDetail, http.Header, error)

RideHistory returns the authenticated user's current and past rides. See the Lyft API reference for details on how far back the start and end times can go. If end is the zero time it is ignored. Limit specifies the maximum number of rides to return. If limit is -1, RideHistory requests the maximum limit documented in the API reference (50).

Implementation detail: The times, in UTC, are formatted using "2006-01-02T15:04:05Z". For example: start.UTC().Format("2006-01-02T15:04:05Z").

func (*Client) RideReceipt

func (c *Client) RideReceipt(rideID string) (RideReceipt, http.Header, error)

RideReceipt retrieves the receipt for the specified ride.

func (*Client) RideTypes

func (c *Client) RideTypes(lat, lng float64, rideType string) ([]RideType, http.Header, error)

RideTypes returns the ride types available at the location. The rideType is optional. If set, details will be returned for the specified ride type only. If no ride types are available, the error will be a StatusError.

func (*Client) SetAccessToken

func (c *Client) SetAccessToken(a string)

func (*Client) SetDestination

func (c *Client) SetDestination(rideID string, loc Location) (Location, http.Header, error)

SetDestination updates the ride's destination to the supplied location. The location's Address field is optional.

func (*Client) UserProfile

func (c *Client) UserProfile() (UserProfile, http.Header, error)

UserProfile returns the authenticated user's profile info.

type CostEstimate

type CostEstimate struct {
	RideType       string
	DisplayName    string
	MaximumCost    int           // Estimated maximum cost of the ride.
	MinimumCost    int           // Estimated minimum cost of the ride.
	Distance       float64       // Estimated distance of the ride; in miles.
	Duration       time.Duration // Estimated duration of the ride.
	PrimetimeToken string        // DEPRECATED; see CostToken and https://developer.lyft.com/reference#availability-ride-estimates.
	CostToken      string
	Valid          bool // If false, MaximumCost and MinimumCost may be invalid.
}

CostEstimate is returned by the client's CostEstimates method.

func (*CostEstimate) UnmarshalJSON

func (r *CostEstimate) UnmarshalJSON(p []byte) error

type CostTokenInfo

type CostTokenInfo struct {
	PrimetimePercentage string
	PrimetimeMultiplier float64
	PrimetimeToken      string
	CostToken           string
	TokenDuration       time.Duration
	ErrorURI            string
}

func (*CostTokenInfo) UnmarshalJSON

func (c *CostTokenInfo) UnmarshalJSON(p []byte) error

type CreatedRide

type CreatedRide struct {
	RideID      string   `json:"ride_id"`
	RideStatus  string   `json:"status"` // StatusPending for newly requested rides
	RideType    string   `json:"ride_type"`
	Origin      Location `json:"origin"`
	Destination Location `json:"destination"`
	Passenger   Person   `json:"passenger"` // The Phone field will not be set
}

CreatedRide is returned by the client's RequestRide method.

type Driver

type Driver struct {
	Locations []LatLng `json:"locations"` // Most recent coordinates (TODO: but in which order? WTF, Lyft API docs)
}

type ETAEstimate

type ETAEstimate struct {
	RideType    string
	DisplayName string
	ETA         time.Duration
	Valid       bool // If false, ETA may be invalid.
}

ETAEstimate is returned by the client's DriverETA method.

func (*ETAEstimate) UnmarshalJSON

func (e *ETAEstimate) UnmarshalJSON(p []byte) error

type ErrorInfo

type ErrorInfo struct {
	Reason      string
	Details     []map[string]string
	Description string
}

type LatLng

type LatLng struct {
	Latitude  float64 `json:"lat"`
	Longitude float64 `json:"lng"`
}

type LineItem

type LineItem struct {
	Amount      int    `json:"amount"`
	Currency    string `json:"currency"`
	Description string `json:"type"`
}

type Location

type Location struct {
	Latitude  float64 `json:"lat"`
	Longitude float64 `json:"lng"`
	Address   string  `json:"address"`
}

type NearbyDriver

type NearbyDriver struct {
	Drivers  []Driver `json:"drivers"`
	RideType string   `json:"ride_type"`
}

NearbyDriver is returned by the client's DriversNearby method.

type Person

type Person struct {
	UserID    string `json:"user_id"`
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	ImageURL  string `json:"image_url"`
	Rating    string `json:"rating"`
	Phone     string `json:"phone_number"`
}

type Price

type Price struct {
	Amount      int    `json:"amount"`
	Currency    string `json:"currency"`
	Description string `json:"description"`
}

type Pricing

type Pricing struct {
	Base            int    `json:"base_charge"`
	PerMile         int    `json:"cost_per_mile"`
	PerMinute       int    `json:"cost_per_minute"`
	Minimum         int    `json:"cost_minimum"`
	TrustAndService int    `json:"trust_and_service"`
	Currency        string `json:"currency"`
	CancelPenalty   int    `json:"cancel_penalty_amount"`
}

type RideDetail

type RideDetail struct {
	RideID              string
	RideStatus          string
	RideType            string
	Origin              RideLocation // Requested location of pickup. The Time field will not be set.
	Pickup              RideLocation // Actual location of pickup. The ETA field will not be set.
	Destination         RideLocation // Requested location of dropoff. The Time field will not be set.
	Dropoff             RideLocation // Actual location of dropoff. The ETA field will not be set.
	Location            VehicleLocation
	Passenger           Person
	Driver              Person
	Vehicle             Vehicle
	PrimetimePercentage string
	Distance            float64
	Duration            time.Duration
	Price               Price
	LineItems           []LineItem
	Requested           time.Time
	RideProfile         string
	BeaconColor         string
	PricingDetailsURL   string
	RouteURL            string
	CanCancel           []string
	CanceledBy          string
	CancellationPrice   CancellationPrice
	Rating              int
	Feedback            string
}

RideDetail is returned by the client's RideDetail and RideHistory methods. Some fields are available only if certain conditions are true at the time of making the request. See the API reference for details. The "generated_at" field is not supported.

func (*RideDetail) UnmarshalJSON

func (r *RideDetail) UnmarshalJSON(p []byte) error

type RideLocation

type RideLocation struct {
	Latitude  float64
	Longitude float64
	Address   string
	ETA       time.Duration
	Time      time.Time
}

type RideReceipt

type RideReceipt struct {
	RideID      string
	Price       Price
	LineItems   []LineItem
	Charges     []Charge
	Requested   time.Time
	RideProfile string
}

RideReceipt is returned by the client's RideReceipt method.

func (*RideReceipt) UnmarshalJSON

func (r *RideReceipt) UnmarshalJSON(p []byte) error

type RideRequest

type RideRequest struct {
	Origin      Location `json:"origin"`      // Latitude and Longitude fields are required
	Destination Location `json:"destination"` // Latitude and Longitude fields are required
	RideType    string   `json:"ride_type"`   // Required
	CostToken   string   `json:"cost_token"`  // Optional
}

RideRequest is the paramters for the client's RequestRide method.

type RideRequestError

type RideRequestError struct {
	ErrorInfo                // Fields may be empty
	Cost      *CostTokenInfo // May be nil
}

func (*RideRequestError) Error

func (c *RideRequestError) Error() string

type RideType

type RideType struct {
	DisplayName string  `json:"display_name"`
	RideType    string  `json:"ride_type"`
	ImageURL    string  `json:"image_url"`
	Pricing     Pricing `json:"pricing_details"`
	Seats       int     `json:"seats"`
}

RideType is returned by the client's RideTypes method.

type StatusError

type StatusError struct {
	StatusCode   int
	ResponseBody bytes.Buffer
	ErrorInfo    // Fields may be empty
}

StatusError is returned when the HTTP roundtrip succeeded, but there was error was indicated via the HTTP status code, typically due to an application-level error.

func NewStatusError

func NewStatusError(rsp *http.Response) *StatusError

NewStatusError is not meant for external use. It exists solely so that subpackages (such as package auth) can create a StatusError in a canonical way.

func (*StatusError) Error

func (s *StatusError) Error() string

type UserProfile

type UserProfile struct {
	ID        string `json:"id"` // Authenticated user's ID.
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	Ridden    bool   `json:"has_taken_a_ride"` // Whether the user has taken at least one ride.
}

UserProfile is returned by the client's UserProfile method.

type Vehicle

type Vehicle struct {
	Make              string `json:"make"`
	Model             string `json:"model"`
	Year              int    `json:"year"`
	LicensePlate      string `json:"license_plate"`
	LicensePlateState string `json:"license_plate_state"`
	Color             string `json:"color"`
	ImageURL          string `json:"image_url"`
}

type VehicleLocation

type VehicleLocation struct {
	Latitude  float64 `json:"lat"`
	Longitude float64 `json:"lng"`
	Bearing   float64 `json:"bearing"` // Bearing of the car in degrees.
}

Directories

Path Synopsis
Package auth and its subpackages define types and functions related to Lyft's OAuth flows.
Package auth and its subpackages define types and functions related to Lyft's OAuth flows.
threeleg
Package threeleg provides functions for working with the three-legged OAuth flow described at https://developer.lyft.com/v1/docs/authentication#section-3-legged-flow-for-accessing-user-specific-endpoints.
Package threeleg provides functions for working with the three-legged OAuth flow described at https://developer.lyft.com/v1/docs/authentication#section-3-legged-flow-for-accessing-user-specific-endpoints.
twoleg
Package twoleg provides functions for working with the two-legged OAuth flow described at https://developer.lyft.com/v1/docs/authentication#section-client-credentials-2-legged-flow-for-public-endpoints.
Package twoleg provides functions for working with the two-legged OAuth flow described at https://developer.lyft.com/v1/docs/authentication#section-client-credentials-2-legged-flow-for-public-endpoints.
Package webhook provides types and utility functions for handling Lyft webhooks.
Package webhook provides types and utility functions for handling Lyft webhooks.

Jump to

Keyboard shortcuts

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