provider.go47 lines, 1.3 KB
| 1 | package fx |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | _ "embed" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | ) |
| 10 | |
| 11 | // ErrNoRate means a provider has no rate for a pair of currencies. |
| 12 | var ErrNoRate = errors.New("fx: no rate") |
| 13 | |
| 14 | // A Provider knows the current mid-market rates: a bank, or a market data |
| 15 | // feed, in production. Rate says how many units of to one unit of from buys. |
| 16 | // It returns an error rather than a stale rate: no quote beats a wrong one. |
| 17 | type Provider interface { |
| 18 | Rate(ctx context.Context, from, to string) (Rate, error) |
| 19 | } |
| 20 | |
| 21 | // Static is a Provider with fixed rates, by pair, like "USD/EUR". For |
| 22 | // development and tests: no network, and the same numbers every time. |
| 23 | type Static map[string]Rate |
| 24 | |
| 25 | func (s Static) Rate(_ context.Context, from, to string) (Rate, error) { |
| 26 | r, ok := s[from+"/"+to] |
| 27 | if !ok { |
| 28 | return 0, fmt.Errorf("%w for %s/%s", ErrNoRate, from, to) |
| 29 | } |
| 30 | return r, nil |
| 31 | } |
| 32 | |
| 33 | //go:embed devrates.json |
| 34 | var devRates []byte |
| 35 | |
| 36 | // DevRates are the development rates, from devrates.json, built into the |
| 37 | // binary. They're made up: in production, env, they're an error. |
| 38 | func DevRates(env string) (Static, error) { |
| 39 | if env == "production" { |
| 40 | return nil, errors.New("fx: the development rates can't price real money: configure a provider") |
| 41 | } |
| 42 | var s Static |
| 43 | if err := json.Unmarshal(devRates, &s); err != nil { |
| 44 | return nil, fmt.Errorf("devrates.json: %w", err) |
| 45 | } |
| 46 | return s, nil |
| 47 | } |