Documentation
¶
Index ¶
- Constants
- Variables
- func Count() (int, error)
- func CountActive() (int, error)
- func CountLegacy() int
- func InitializeGlobalRegistry(ctx context.Context, redisURL ...string) error
- func IsSupported(code string) bool
- func IsSupportedLegacy(code string) bool
- func IsValidFormat(code string) bool
- func Legacy(code string, meta Meta)
- func ListSupported() ([]string, error)
- func ListSupportedLegacy() []string
- func Register(meta Meta) error
- func Unregister(code string) error
- func UnregisterLegacy(code string) bool
- type Code
- type Entity
- type Meta
- type Registry
- func (cr *Registry) Activate(code string) error
- func (cr *Registry) Count() (int, error)
- func (cr *Registry) CountActive() (int, error)
- func (cr *Registry) Deactivate(code string) error
- func (cr *Registry) Get(code string) (Meta, error)
- func (cr *Registry) GetRegistry() registry.Provider
- func (cr *Registry) IsSupported(code string) bool
- func (cr *Registry) ListAll() ([]Meta, error)
- func (cr *Registry) ListSupported() ([]string, error)
- func (cr *Registry) Register(meta Meta) error
- func (cr *Registry) Search(query string) ([]Meta, error)
- func (cr *Registry) SearchByRegion(region string) ([]Meta, error)
- func (cr *Registry) SetRegistry(reg registry.Provider)
- func (cr *Registry) Unregister(code string) error
- type Validator
Examples ¶
Constants ¶
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 ¶
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
var Get = getCurrencyInternal
Get returns currency metadata for the given code
Functions ¶
func CountActive ¶
func CountLegacy ¶
func CountLegacy() int
func InitializeGlobalRegistry ¶
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 IsSupportedLegacy ¶
func IsValidFormat ¶
IsValidFormat returns true if the code is a well-formed ISO 4217 currency code (3 uppercase letters).
func ListSupported ¶
func ListSupportedLegacy ¶
func ListSupportedLegacy() []string
func Unregister ¶
func UnregisterLegacy ¶
Types ¶
type Entity ¶
type Entity struct {
*registry.BaseEntity
// contains filtered or unexported fields
}
Entity implements the registry.Entity interface
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 SearchByRegion ¶
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 ¶
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) Count ¶
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 ¶
CountActive returns the number of active currencies
func (*Registry) Deactivate ¶
Deactivate deactivates a currency
func (*Registry) Get ¶
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 ¶
GetRegistry returns the underlying registry provider
func (*Registry) IsSupported ¶
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) ListSupported ¶
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 ¶
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 ¶
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 ¶
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) SetRegistry ¶ added in v1.2.0
func (*Registry) Unregister ¶
Unregister removes a currency from the registry