currency

package
v1.118.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2025 License: Apache-2.0 Imports: 7 Imported by: 0

README

Currency Package

Convert costs between currencies in OpenCost using live exchange rates. This package provides a reusable currency conversion utility for OpenCost components and plugins.

Quick Start

import "github.com/opencost/opencost/pkg/currency"

config := currency.Config{
    APIKey:   "your-api-key",
    CacheTTL: 24 * time.Hour,
}

converter, err := currency.NewConverter(config)
if err != nil {
    log.Fatal(err)
}

// Convert 100 USD to EUR
amount, err := converter.Convert(100.0, "USD", "EUR")

Setup

Get a free API key from exchangerate-api.com (1,500 requests/month).

How it Works

The package fetches exchange rates and caches them for 24 hours. This keeps API usage low - most plugins use under 50 requests per month.

Supports all ISO 4217 currencies (161 total). Thread-safe with automatic cache cleanup.

Example Usage in Plugins

// Plugin config
type PluginConfig struct {
    TargetCurrency  string `json:"target_currency"`
    ExchangeAPIKey  string `json:"exchange_api_key"`
}

// Initialize converter
if config.ExchangeAPIKey != "" {
    converter, _ := currency.NewConverter(currency.Config{
        APIKey:   config.ExchangeAPIKey,
        CacheTTL: 24 * time.Hour,
    })
}

// Convert costs
if converter != nil {
    cost, _ = converter.Convert(cost, "USD", targetCurrency)
}

Testing

cd pkg/currency
go test -v

Tests use mocks - no API calls needed.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	APIKey     string
	CacheTTL   time.Duration
	APITimeout time.Duration
}

Config holds configuration for the currency converter

type Converter

type Converter interface {
	// Convert converts an amount from one currency to another
	Convert(amount float64, from, to string) (float64, error)

	// GetRate returns the exchange rate between two currencies
	GetRate(from, to string) (float64, error)
}

Converter interface defines currency conversion operations

func NewConverter

func NewConverter(config Config) (Converter, error)

Jump to

Keyboard shortcuts

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