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

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

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

This section is empty.

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

      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)

          Expire will expire the cache for a given base currency.

          func (*CacheService) Get

          func (s *CacheService) Get(base string) (*RateResposne, bool)

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

            func (*CacheService) IsExpired

            func (s *CacheService) IsExpired(base string) bool

              IsExpired checks whether or not rate stored is expired.

              func (*CacheService) Store

              func (s *CacheService) Store(rsp *RateResposne)

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

                        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

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

                            CurrenciesService handles currency request/responses.

                            func NewCurrenciesService

                            func NewCurrenciesService(
                            	client *Client,
                            ) *CurrenciesService

                              NewCurrenciesService creates a new handler for this service.

                              func (*CurrenciesService) List

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

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

                                type CurrencyResponse

                                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 RateResposne

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

                                      RateResposne 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

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

                                          NewRatesService creates a new handler for this service.

                                          func (*RatesService) Get

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

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

                                            func (*RatesService) GetBaseCurrency

                                            func (s *RatesService) GetBaseCurrency() string

                                              GetBaseCurrency will return the baseCurrency.

                                              func (*RatesService) List

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

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

                                                func (*RatesService) SetBaseCurrency

                                                func (s *RatesService) SetBaseCurrency(base string)

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

                                                  func (*RatesService) Update

                                                  func (s *RatesService) Update(base string) error

                                                    Update will update the rates for the given currency from OXR.

                                                    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.