currency

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 5, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	// DefaultCode is the fallback currency code (USD)
	DefaultCode = "USD"
	// DefaultDecimals is the default number of decimal places for currencies
	DefaultDecimals = 2
	// MaxDecimals is the maximum number of decimal places allowed
	MaxDecimals = 18
	// MaxSymbolLength is the maximum length for currency symbols
	MaxSymbolLength = 10

	USD = Code("USD")
	EUR = Code("EUR")

	Default = USD
)

Variables

View Source
var (
	ErrInvalidCode = errors.New(
		"invalid currency code: must be 3 uppercase letters")
	ErrInvalidDecimals = errors.New("invalid decimals: must be between 0 and 8")
	ErrInvalidSymbol   = errors.New(
		"invalid symbol: must not be empty and max 10 characters")
	ErrCurrencyNotFound = errors.New("currency not found")
	ErrCurrencyExists   = errors.New("currency already exists")
)

Common errors

Functions

func Count

func Count() (int, error)

func CountActive

func CountActive() (int, error)

func CountLegacy

func CountLegacy() int

func InitializeGlobalRegistry

func InitializeGlobalRegistry(ctx context.Context, redisURL ...string) error

InitializeGlobalRegistry initializes the global currency registry with optional Redis configuration. If redisURL is provided, it will be used to configure Redis caching. If keyPrefix is provided, it will be used as the Redis key prefix. If redisURL is empty, an in-memory cache will be used.

This function should be called during application startup.

func IsSupported

func IsSupported(code string) bool

func IsSupportedLegacy

func IsSupportedLegacy(code string) bool

func IsValidFormat

func IsValidFormat(code string) bool

IsValidFormat returns true if the code is a well-formed ISO 4217 currency code (3 uppercase letters).

func Legacy

func Legacy(code string, meta Meta)

Legacy Backward compatibility functions (deprecated)

func ListSupported

func ListSupported() ([]string, error)

func ListSupportedLegacy

func ListSupportedLegacy() []string

func Register

func Register(meta Meta) error

Register Global convenience functions with error handling

func Unregister

func Unregister(code string) error

func UnregisterLegacy

func UnregisterLegacy(code string) bool

Types

type Code

type Code string

Code represents a 3-letter ISO currency code

func (Code) String

func (c Code) String() string

String return code as string

type Entity

type Entity struct {
	*registry.BaseEntity
	// contains filtered or unexported fields
}

Entity implements the registry.Entity interface

func NewEntity

func NewEntity(meta Meta) *Entity

NewEntity creates a new currency entity

func (*Entity) Active

func (c *Entity) Active() bool

Active returns whether the currency is active

func (*Entity) Code

func (c *Entity) Code() string

Code returns the currency code

func (*Entity) CreatedAt

func (c *Entity) CreatedAt() time.Time

CreatedAt returns the creation timestamp

func (*Entity) Meta

func (c *Entity) Meta() Meta

Meta returns the currency metadata

func (*Entity) Metadata

func (c *Entity) Metadata() map[string]string

Metadata returns currency metadata

func (*Entity) Name

func (c *Entity) Name() string

Name returns the currency name

func (*Entity) UpdatedAt

func (c *Entity) UpdatedAt() time.Time

UpdatedAt returns the last update timestamp

type Meta

type Meta struct {
	Code     string            `json:"code"`
	Name     string            `json:"name"`
	Symbol   string            `json:"symbol"`
	Decimals int               `json:"decimals"`
	Country  string            `json:"country,omitempty"`
	Region   string            `json:"region,omitempty"`
	Active   bool              `json:"active"`
	Metadata map[string]string `json:"metadata,omitempty"`
	Created  time.Time         `json:"created"`
	Updated  time.Time         `json:"updated"`
}

Meta holds currency-specific metadata

func Get

func Get(code string) (Meta, error)
Example

ExampleGet demonstrates basic currency operations

// Get currency information
usd, err := Get("USD")
if err != nil {
	log.Fatal(err)
}
fmt.Printf("USD: %s (%s) - %d decimals\n", usd.Name, usd.Symbol, usd.Decimals)

// Check if currency is supported
if IsSupported("EUR") {
	fmt.Println("EUR is supported")
}

// List all supported currencies
supported, err := ListSupported()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Total supported currencies: %d\n", len(supported))
Output:

USD: US Dollar ($) - 2 decimals
EUR is supported
Total supported currencies: 13

func GetLegacy

func GetLegacy(code string) Meta

func ListAll

func ListAll() ([]Meta, error)
func Search(query string) ([]Meta, error)

func SearchByRegion

func SearchByRegion(region string) ([]Meta, error)

type Registry

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

Registry provides currency-specific operations using the registry system

func GetGlobalRegistry

func GetGlobalRegistry() *Registry

GetGlobalRegistry returns the global currency registry instance. Make sure to call InitializeGlobalRegistry first to initialize the registry.

func New

func New(ctx context.Context, params ...string) (*Registry, error)

New creates a new currency registry with default currencies If redisURL is provided, it will use Redis for caching The function accepts optional parameters in this order: redisURL, keyPrefix

Example

ExampleNewRegistry demonstrates creating a custom currency registry

ctx := context.Background()

// Create a new registry
registry, err := New(ctx)
if err != nil {
	log.Fatal(err)
}

// Register a custom cryptocurrency
crypto := Meta{
	Code:     "BTC",
	Name:     "Bitcoin",
	Symbol:   "₿",
	Decimals: 8,
	Country:  "Global",
	Region:   "Digital",
	Active:   true,
	Metadata: map[string]string{
		"type":       "cryptocurrency",
		"blockchain": "Bitcoin",
		"max_supply": "21000000",
	},
}

if err = registry.Register(crypto); err != nil {
	log.Fatal(err)
}

// Retrieve the currency
retrieved, err := registry.Get("BTC")
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Registered: %s (%s)\n", retrieved.Name,
	retrieved.Symbol)
Output:

Registered: Bitcoin (₿)

func NewRegistryWithPersistence

func NewRegistryWithPersistence(
	ctx context.Context, persistencePath string, redisURL ...string,
) (*Registry, error)

NewRegistryWithPersistence creates a currency registry with persistence If redisURL is provided, it will use Redis for caching

Example

ExampleNewRegistryWithPersistence demonstrates using persistence with currency registry

ctx := context.Background()

// Create registry with persistence
registry, err := NewRegistryWithPersistence(ctx, "./currencies.json")
if err != nil {
	log.Fatal(err)
}

// Register a new currency
newCurrency := Meta{
	Code:     "CST",
	Name:     "Custom Currency",
	Symbol:   "C",
	Decimals: 2,
	Country:  "Custom Country",
	Region:   "Custom Region",
	Active:   true,
}

if err := registry.Register(newCurrency); err != nil {
	log.Fatal(err)
}

// The currency will be automatically saved to the file
fmt.Println("Currency registered and persisted")
Output:

Currency registered and persisted

func (*Registry) Activate

func (cr *Registry) Activate(code string) error

Activate activates a currency

func (*Registry) Count

func (cr *Registry) Count() (int, error)

Count returns the total number of registered currencies

Example

ExampleCurrencyRegistry_Count demonstrates getting currency statistics

ctx := context.Background()
registry, err := New(ctx)
if err != nil {
	log.Fatal(err)
}

// Register some currencies
currencies := []Meta{
	{Code: "USD", Name: "US Dollar", Symbol: "$", Decimals: 2, Active: true},
	{Code: "EUR", Name: "Euro", Symbol: "€", Decimals: 2, Active: true},
	{Code: "INA", Name: "Inactive Currency", Symbol: "I", Decimals: 2, Active: false},
}

for _, currency := range currencies {
	if err := registry.Register(currency); err != nil {
		log.Println(err)
		continue
	}
}

// Get counts
total, _ := registry.Count()
active, _ := registry.CountActive()
fmt.Printf("Total currencies: %d\n", total)
fmt.Printf("Active currencies: %d\n", active)
fmt.Printf("Inactive currencies: %d\n", total-active)
Output:

Total currencies: 13
Active currencies: 12
Inactive currencies: 1

func (*Registry) CountActive

func (cr *Registry) CountActive() (int, error)

CountActive returns the number of active currencies

func (*Registry) Deactivate

func (cr *Registry) Deactivate(code string) error

Deactivate deactivates a currency

func (*Registry) Get

func (cr *Registry) Get(code string) (Meta, error)

Get returns currency metadata for the given code

Example

ExampleRegistry_Get demonstrates working with currency events

ctx := context.Background()
registry, err := New(ctx)
if err != nil {
	log.Fatal(err)
}

// Register a currency
currency := Meta{
	Code:     "TST",
	Name:     "Test Currency",
	Symbol:   "T",
	Decimals: 2,
	Active:   true,
}

err = registry.Register(currency)
if err != nil {
	fmt.Printf("Registration failed: %v\n", err)
} else {
	fmt.Println("Currency registered successfully")
}

// Unregister the currency
err = registry.Unregister("TST")
if err != nil {
	fmt.Printf("Unregistration failed: %v\n", err)
} else {
	fmt.Println("Currency unregistered successfully")
}
Output:

Currency registered successfully
Currency unregistered successfully

func (*Registry) GetRegistry

func (cr *Registry) GetRegistry() registry.Provider

GetRegistry returns the underlying registry provider

func (*Registry) IsSupported

func (cr *Registry) IsSupported(code string) bool

IsSupported checks if a currency code is registered and active

Example

ExampleRegistry_IsSupported demonstrates the caching behavior

ctx := context.Background()
registry, err := New(ctx)
if err != nil {
	log.Fatal(err)
}

// First lookup (cache miss)
currency1, _ := registry.Get("USD")

// Second lookup (cache hit)
currency2, _ := registry.Get("USD")

fmt.Printf("Same currency: %t\n", currency1.Code == currency2.Code)
Output:

Same currency: true

func (*Registry) ListAll

func (cr *Registry) ListAll() ([]Meta, error)

ListAll returns all registered currencies (active and inactive)

func (*Registry) ListSupported

func (cr *Registry) ListSupported() ([]string, error)

ListSupported returns a list of all supported currency codes

Example

ExampleRegistry_ListSupported demonstrates health checking

ctx := context.Background()
registry, err := New(ctx)
if err != nil {
	log.Fatal(err)
}

// Check if registry is working by getting a currency
_, err = registry.Get("USD")
if err != nil {
	fmt.Printf("Registry unhealthy: %v\n", err)
} else {
	fmt.Println("Registry is healthy")
}

// Get total count
total, _ := registry.Count()
fmt.Printf("Total currencies: %d\n", total)
Output:

Registry is healthy
Total currencies: 12

func (*Registry) Register

func (cr *Registry) Register(meta Meta) error

Register adds or updates a currency in the registry

Example

ExampleRegistry_Register demonstrates currency lifecycle management

ctx := context.Background()
registry, err := New(ctx)
if err != nil {
	log.Fatal(err)
}

// Register a currency as inactive
currency := Meta{
	Code:     "TST",
	Name:     "Test Currency",
	Symbol:   "T",
	Decimals: 2,
	Active:   false, // Start as inactive
}

if err := registry.Register(currency); err != nil {
	log.Fatal(err)
}

// Initially not supported (inactive)
fmt.Printf("Is TEST supported? %t\n", registry.IsSupported("TST"))

// Activate the currency
if err := registry.Activate("TST"); err != nil {
	log.Fatal(err)
}
fmt.Printf("After activation, is TEST supported? %t\n", registry.IsSupported("TST"))

// Deactivate the currency
if err := registry.Deactivate("TST"); err != nil {
	log.Fatal(err)
}
fmt.Printf("After deactivation, is TEST supported? %t\n", registry.IsSupported("TST"))

// Unregister the currency
if err := registry.Unregister("TST"); err != nil {
	log.Fatal(err)
}
fmt.Println("Currency unregistered")
Output:

Is TEST supported? false
After activation, is TEST supported? true
After deactivation, is TEST supported? false
Currency unregistered

func (*Registry) Search

func (cr *Registry) Search(query string) ([]Meta, error)

Search searches for currencies by name

Example

ExampleRegistry_Search demonstrates searching for currencies

ctx := context.Background()
registry, err := New(ctx)
if err != nil {
	log.Fatal(err)
}

// Search by name
results, err := registry.Search("Dollar")
if err != nil {
	log.Fatal(err)
}

sort.Slice(results, func(i, j int) bool {
	return results[i].Name < results[j].Name
})

fmt.Println("Currencies with 'Dollar' in name:")
for _, currency := range results {
	fmt.Printf("- %s (%s) from %s\n",
		currency.Name, currency.Symbol, currency.Country)
}
Output:

Currencies with 'Dollar' in name:
- Australian Dollar (A$) from Australia
- Canadian Dollar (C$) from Canada
- US Dollar ($) from United States

func (*Registry) SearchByRegion

func (cr *Registry) SearchByRegion(region string) ([]Meta, error)

SearchByRegion searches for currencies by region

Example

ExampleRegistry_SearchByRegion demonstrates searching by region

ctx := context.Background()
registry, err := New(ctx)
if err != nil {
	log.Fatal(err)
}

// Search by region
european, err := registry.SearchByRegion("Europe")
if err != nil {
	log.Fatal(err)
}

sort.Slice(european, func(i, j int) bool {
	return european[i].Name < european[j].Name
})

fmt.Println("European currencies:")
for _, currency := range european {
	fmt.Printf("- %s (%s)\n", currency.Name, currency.Symbol)
}
Output:

European currencies:
- British Pound (£)
- Euro (€)
- Swiss Franc (CHF)

func (*Registry) Unregister

func (cr *Registry) Unregister(code string) error

Unregister removes a currency from the registry

type Validator

type Validator struct{}

Validator implements registry.Validator for currency entities

func NewCurrencyValidator

func NewCurrencyValidator() *Validator

NewCurrencyValidator creates a new currency validator

func (*Validator) Validate

func (cv *Validator) Validate(ctx context.Context, entity registry.Entity) error

Validate validates a currency entity

func (*Validator) ValidateMetadata

func (cv *Validator) ValidateMetadata(ctx context.Context, metadata map[string]string) error

ValidateMetadata validates currency metadata

Jump to

Keyboard shortcuts

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