dinero

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2021 License: MIT Imports: 10 Imported by: 1

README

dinero

GoDoc Build Status Go Report Card license

dinero is a Go client library for accessing the Open Exchange Rates API (https://docs.openexchangerates.org/docs/).

Any forex rates requested will be cached (in-memory), keyed by base currency. With a customisable expiry window, subsequent requests will use cached data or fetch fresh data accordingly.

Installation

go get -u github.com/mattevans/dinero

Usage

Intialize

// Init dinero client passing....
// - your OXR app ID
// - base currency code for conversions to work from
// - your preferrerd cache expiry
client := NewClient(
  os.Getenv("OPEN_EXCHANGE_APP_ID"), 
  "AUD",
  20*time.Minute,
)

Currencies

List

// List all currencies available.
rsp, err := client.Currencies.List()
if err != nil {
  return err
}
[
  {
    "code": "INR",
    "name": "Indian Rupee"
  },
  {
    "code": "PYG",
    "name": "Paraguayan Guarani"
  },
  {
      "code": "AED",
      "name": "United Arab Emirates Dirham"
  },
  ...
}

Rates

List

// List latest forex rates. This will use AUD (defined when intializing the client) as the base.
rsp, err := client.Rates.List()
if err != nil {
  return err
}
{
   "rates":{
      "AED": 2.702388,
      "AFN": 48.893275,
      "ALL": 95.142814,
      "AMD": 356.88691,
      ...
   },
   "base": "AUD"
}

Get

// Get latest forex rate for NZD. This will use AUD (defined when intializing the client) as the base.
rsp, err := client.Rates.Get("NZD")
if err != nil {
  return err
}
1.045545

Historical Rates

List

historicalDate := time.Now().AddDate(0, -5, -3)

// List historical forex rates. This will use AUD (defined when intializing the client) as the base.
rsp, err := client.Historical.List(historicalDate)
if err != nil {
  return err
}
{
   "rates":{
      "AED": 2.702388,
      "AFN": 48.893275,
      "ALL": 95.142814,
      "AMD": 356.88691,
      ...
   },
   "base": "AUD"
}

Get

historicalDate := time.Now().AddDate(0, -5, -3)

// Get historical forex rate for NZD. This will use AUD (defined when intializing the client) as the base.
rsp, err := client.Rates.Get("NZD", historicalDate)
if err != nil {
  return err
}
1.045545

Change Base Currency

You set a base currency when you the intialize dinero client. Should you wish to change this at anytime, you can call...

client.Rates.SetBaseCurrency("USD")

NOTE: Changing the API base currency is available for Developer, Enterprise and Unlimited plan clients only.


Expire

You set your preferred cache expiry interval when you intialize the dinero client. By default, cached rates will expire themselves based on your configured interval.

You can force an expiry of the rates for your currency set by calling...

client.Cache.Expire()

Contributing

If you've found a bug or would like to contribute, please create an issue here on GitHub, or better yet fork the project and submit a pull request!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrRatesNotFound is returned if no rate can be found for a given currency code.
	ErrRatesNotFound = errors.New("no rates found for code")
)

Functions

func CheckResponse

func CheckResponse(r *http.Response) error

CheckResponse checks the API response for errors. A response is considered an error if it has a status code outside the 200 range. API error responses map to ErrorResponse.

Types

type CacheService

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

CacheService handles in-memory caching of our rates.

func NewCacheService added in v0.3.0

func NewCacheService(
	client *Client,
	store *cache.Cache,
) *CacheService

NewCacheService creates a new handler for this service.

func (*CacheService) Expire

func (s *CacheService) Expire(base string, date time.Time)

Expire will expire the cache for a given base currency.

func (*CacheService) Get

func (s *CacheService) Get(base string, date time.Time) (*RateResponse, bool)

Get will return our in-memory stored currency/rates.

func (*CacheService) IsExpired

func (s *CacheService) IsExpired(base string, date time.Time) bool

IsExpired checks whether the rate stored is expired.

func (*CacheService) Store

func (s *CacheService) Store(rsp *RateResponse, date time.Time)

Store will store our currency/rates in-memory.

type Client

type Client struct {

	// AppID is the Open Exchange Rates application ID.
	AppID string
	// UserAgent is the UA for this package that all requests will use.
	UserAgent string
	// BackendURL is the base API endpoint at OXR.
	BackendURL *url.URL

	// Services used for communicating with the API.
	Rates           *RatesService
	HistoricalRates *HistoricalRatesService
	Currencies      *CurrenciesService
	Cache           *CacheService
	// contains filtered or unexported fields
}

Client holds a connection to the OXR API.

func NewClient

func NewClient(appID, baseCurrency string, expiry time.Duration) *Client

NewClient creates a new Client with the appropriate connection details and services used for communicating with the API.

func (*Client) Do

func (c *Client) Do(req *http.Request, v interface{}) (*Response, error)

Do sends an API request and returns the API response. The API response is JSON decoded and stored in 'v', or returned as an error if an API (if found).

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlPath string, params url.Values, body interface{}) (*http.Request, error)

NewRequest creates an authenticated API request. A relative URL can be provided in urlPath, which will be resolved to the BackendURL of the Client.

func (*Client) NewUnauthedRequest added in v0.4.0

func (c *Client) NewUnauthedRequest(method, urlPath string, body interface{}) (*http.Request, error)

NewUnauthedRequest creates an unauthenticated API request. A relative URL can be provided in urlPath, which will be resolved to the BackendURL of the Client.

type CurrenciesService added in v0.4.0

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

CurrenciesService handles currency request/responses.

func NewCurrenciesService added in v0.4.0

func NewCurrenciesService(
	client *Client,
) *CurrenciesService

NewCurrenciesService creates a new handler for this service.

func (*CurrenciesService) List added in v0.4.0

func (s *CurrenciesService) List() ([]*CurrencyResponse, error)

List will fetch all list of all currencies available via the OXR api.

type CurrencyResponse added in v0.4.0

type CurrencyResponse struct {
	Code string `json:"code"`
	Name string `json:"name"`
}

CurrencyResponse represents a currency from OXR.

type ErrorResponse

type ErrorResponse struct {
	*http.Response
	ErrorCode   int64  `json:"status"`
	Message     string `json:"message"`
	Description string `json:"description"`
}

An ErrorResponse reports the error caused by an API request

func (*ErrorResponse) Error

func (r *ErrorResponse) Error() string

type HistoricalRatesResponse added in v0.8.0

type HistoricalRatesResponse struct {
	Rates     map[string]float64 `json:"rates"`
	Base      string             `json:"base"`
	Timestamp int64              `json:"timestamp"`
}

HistoricalRatesResponse holds our forex rates for a given base currency

type HistoricalRatesService added in v0.8.0

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

HistoricalRatesService handles historical rate request/responses.

func NewHistoricalRatesService added in v0.8.0

func NewHistoricalRatesService(
	client *Client,
	baseCurrency string,
) *HistoricalRatesService

NewHistoricalRatesService creates a new handler for this service.

func (*HistoricalRatesService) Get added in v0.8.0

func (s *HistoricalRatesService) Get(code string, date time.Time) (*float64, error)

Get will fetch a single rate for a given currency either from the store or the OXR api.

func (*HistoricalRatesService) GetBaseCurrency added in v0.8.0

func (s *HistoricalRatesService) GetBaseCurrency() string

GetBaseCurrency will return the baseCurrency.

func (*HistoricalRatesService) List added in v0.8.0

List will fetch all the latest rates for the base currency either from the store or the OXR api.

func (*HistoricalRatesService) SetBaseCurrency added in v0.8.0

func (s *HistoricalRatesService) SetBaseCurrency(base string)

SetBaseCurrency will set the base currency to be used for requests.

type RateResponse added in v0.6.0

type RateResponse struct {
	Rates     map[string]float64 `json:"rates"`
	Base      string             `json:"base"`
	Timestamp int64              `json:"timestamp"`
}

RateResponse holds our forex rates for a given base currency

type RatesService

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

RatesService handles rate request/responses.

func NewRatesService added in v0.3.0

func NewRatesService(
	client *Client,
	baseCurrency string,
) *RatesService

NewRatesService creates a new handler for this service.

func (*RatesService) Get added in v0.3.0

func (s *RatesService) Get(code string) (*float64, error)

Get will fetch a single rate for a given currency either from the store or the OXR api.

func (*RatesService) GetBaseCurrency

func (s *RatesService) GetBaseCurrency() string

GetBaseCurrency will return the baseCurrency.

func (*RatesService) List added in v0.3.0

func (s *RatesService) List() (*RateResponse, error)

List will fetch all the latest rates for the base currency either from the store or the OXR api.

func (*RatesService) ListHistorical added in v0.7.0

func (s *RatesService) ListHistorical(date time.Time) (*RateResponse, error)

ListHistorical will fetch all rates for the base currency for the given time.Time.

func (*RatesService) SetBaseCurrency

func (s *RatesService) SetBaseCurrency(base string)

SetBaseCurrency will set the base currency to be used for requests.

type Response

type Response struct {
	*http.Response
	ErrorCode int64
	Message   string
}

Response is a OXR response. This wraps the standard http.Response returned from the OXR API.

Jump to

Keyboard shortcuts

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