Guide
Exchange rates in Go: a typed client, one cached reading, correct rounding
net/http, typed structs, a mutex-guarded cache and rounding you can defend.
What this covers
Go makes the request easy and the details easy to get wrong: a client with no timeout, a reading re-fetched per handler, and a float rounded at the wrong moment are all one-line mistakes with expensive consequences.
This is a client you would keep: one struct per half of the response, one reading cached behind a mutex, money rounded at the last step, and errors that are typed by what the server actually said.
A typed read with a real timeout
Decode into structs rather than a map: the compiler then tells you when a field name changes. The envelope is meta (base, count, reading timestamp) plus data.latest.rates, the quote map.
Always put the deadline on the request context, not just on the client — a handler that is already cancelled should not start a call it will throw away.
rates/client.go
package rates
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
type Envelope struct {
Meta struct {
BaseCurrency string `json:"base_currency"`
CurrencyCount int `json:"currency_count"`
UpdatedAt time.Time `json:"updated_at"`
} `json:"meta"`
Data struct {
Latest struct {
Rates map[string]float64 `json:"rates"`
} `json:"latest"`
} `json:"data"`
}
func Fetch(ctx context.Context, key string) (*Envelope, error) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
endpoint := "https://fiatagent.base44.app/api/v1/public/rates"
if key != "" { endpoint = "https://fiatagent.base44.app/api/v1/rates?snapshots=1" }
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
if key != "" {
req.Header.Set("Authorization", "Bearer "+key)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("fiat agent: %s", res.Status)
}
var env Envelope
if err := json.NewDecoder(res.Body).Decode(&env); err != nil {
return nil, err
}
return &env, nil
}One reading per process, behind a mutex
A rate reading is the same for every goroutine in the process, so caching it is the difference between one request per fifteen minutes and one per HTTP handler call. The example cache uses a keyed request for continuous workloads. On the no-key endpoint, polling every fifteen minutes would exceed the daily window.
The mutex also collapses a thundering herd — the first caller fetches, the rest wait and then read the cached value.
rates/cache.go
package rates
import (
"context"
"sync"
"time"
)
type Cache struct {
mu sync.Mutex
at time.Time
payload *Envelope
}
const ttl = 15 * time.Minute
func (c *Cache) Get(ctx context.Context, key string) (*Envelope, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.payload != nil && time.Since(c.at) < ttl {
return c.payload, nil
}
env, err := Fetch(ctx, key)
if err != nil {
return nil, err
}
c.at, c.payload = time.Now(), env
return env, nil
}Round once, at the last step
Round the converted amount, never the rate: rounding a rate to four decimals and then multiplying a large amount drifts visibly. And round to the minor unit of the target currency — zero decimals for JPY, three for KWD.
For ledgers and invoices, go a step further and keep money as int64 minor units plus a decimal library. float64 is fine for a display price and not fine for an accounting entry.
rates/convert.go
func Convert(amount, rate float64, decimals int) float64 {
scale := math.Pow(10, float64(decimals))
return math.Round(amount*rate*scale) / scale
}
// Both quotes share one base, so any pair is a single division.
eurPerUSD := env.Data.Latest.Rates["EUR"]
gbpPerUSD := env.Data.Latest.Rates["GBP"]
gbpPerEUR := gbpPerUSD / eurPerUSD
fmt.Println(Convert(49.99, gbpPerEUR, 2)) // depends on the stored readingRetry the transient failure only
The server distinguishes its failures by status, and so should your client. 400 and 401 are bugs in the request or the credential — retrying them is a way to turn a typo into a loop. 503 is a transient store read, and its retry-after header says how long to wait.
Wrapping the wait in a select on ctx.Done() means a cancelled request stops waiting instead of holding a goroutine for the backoff.
rates/errors.go
switch res.StatusCode {
case http.StatusOK:
// decode as above
case http.StatusBadRequest, http.StatusUnauthorized, http.StatusPaymentRequired:
return nil, fmt.Errorf("fiat agent: %s (not retryable)", res.Status)
case http.StatusTooManyRequests, http.StatusServiceUnavailable:
wait, _ := strconv.Atoi(res.Header.Get("Retry-After"))
if wait == 0 {
wait = 2
}
select {
case <-time.After(time.Duration(wait) * time.Second):
return nil, errShouldRetry
case <-ctx.Done():
return nil, ctx.Err()
}
}Common questions
Should I use http.DefaultClient in production?
Only with a per-request context deadline and a transport you control. A named client with its own http.Transport, timeouts and a connection pool tuned for your concurrency is the safer default.
Do I need an API key in Go?
Not to start: the open endpoint answers without one at 5 a second, 50 an hour and 50 a day per client. A key trades those windows for per-key burst limits, opens with a 2,000-request signup bonus plus 200 conversions, and reaches the stored history — which is what you want for anything server-side and continuous.
How do I read history in Go?
Add ?from= and ?to= as UTC dates to the keyed request — or ?snapshots=N for the most recent N readings — and decode the snapshots array, which is sorted newest first.
Run it against the real thing.
The open endpoint needs no key, so you can paste these samples into a terminal before you sign up for anything.