Tutorial/Go quickstart

Get exchange rates in Go with net/http

Build a small, typed Go client for exchangerate.dev with net/http, context timeouts, environment-based authentication, and explicit freshness fields.

ERexchangerate.dev·Sep 8, 2026·6 min read

The standard library is enough for a reliable Go integration. Keep the API key in the process environment, reject non-2xx responses before decoding JSON, and retain source, market_session, and data_updated_at beside every rate.

Key points
Use net/http with a bounded context instead of an unbounded request.
Decode rates into a typed struct and preserve the observation metadata.
Send the bearer key from EXCHANGERATE_API_KEY; never commit it.
Treat 401, 429, and other non-2xx responses as errors before decoding.

Create a typed client with net/http

Save this complete program as main.go. It requests three symbols in one call and preserves numeric tokens as json.Number; use an exact-decimal library before doing money arithmetic. The anonymous request is useful for evaluation; set EXCHANGERATE_API_KEY when the application has a key. context.WithTimeout prevents a stalled network connection from holding a worker forever.

go · main.gocopy
package main

import (
  "context"
  "encoding/json"
  "fmt"
  "net/http"
  "log"
  "os"
  "regexp"
  "strings"
  "time"
)

type Latest struct {
  Base          string             `json:"base"`
  Source        string             `json:"source"`
  MarketSession string             `json:"market_session"`
  UpdatedAt     time.Time          `json:"data_updated_at"`
  Sources       map[string]string  `json:"sources"`
  EffectiveAt   map[string]string  `json:"effective_at"`
  Rates         map[string]json.Number `json:"rates"`
}

func LatestRates(ctx context.Context, base string) (Latest, error) {
  base = strings.ToUpper(base)
  if !regexp.MustCompile("^[A-Z]{3}$").MatchString(base) {
    return Latest{}, fmt.Errorf("invalid base currency: %q", base)
  }
  url := "https://api.exchangerate.dev/v1/latest/" + base + "?symbols=EUR,GBP,JPY"
  req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
  if err != nil { return Latest{}, err }
  if key := os.Getenv("EXCHANGERATE_API_KEY"); key != "" {
    req.Header.Set("Authorization", "Bearer "+key)
  }

  client := &http.Client{Timeout: 5 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
    return http.ErrUseLastResponse
  }}
  res, err := client.Do(req)
  if err != nil { return Latest{}, err }
  defer res.Body.Close()
  if res.StatusCode < 200 || res.StatusCode >= 300 {
    return Latest{}, fmt.Errorf("exchange rate API: HTTP %s", res.Status)
  }
  var out Latest
  if err := json.NewDecoder(res.Body).Decode(&out); err != nil { return Latest{}, err }
  return out, nil
}

func main() {
  ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  defer cancel()
  latest, err := LatestRates(ctx, "USD")
  if err != nil { log.Fatal(err) }
  fmt.Println(latest.Rates["EUR"], latest.Sources["EUR"], latest.EffectiveAt["EUR"])
}

Call it with a timeout

shell · run main.gocopy
go run main.go

Handle errors and freshness explicitly

Do not decode an error body as if it were a successful rate response. A 401 means the key or authorization header needs correction. A 429 means the caller should slow down and respect its plan. Retry only bounded, transient failures such as a network timeout or selected 5xx responses, with backoff.

Keep the rate and its meaning together
Persist source, market_session, and data_updated_at with the number. Actively traded currencies can update intraday on trading days; daily-reference currencies do not become live because the client polled more often.
  • Reuse an http.Client with an explicit transport timeout in production.
  • Cache only successful responses.
  • Use decimal arithmetic for money calculations at the application boundary.
  • Never expose EXCHANGERATE_API_KEY in browser or mobile builds.
ER
exchangerate.dev
Integration guides for developers building with FX data.

Keep reading

ReferenceExchange rate API quickstartRead TutorialExchange rates in PythonRead ReferenceReading source and market_sessionRead
More ComparisonsFixer vs exchangerate.devOpen Exchange Rates vs exchangerate.devCurrencylayer vs exchangerate.devCurrencylayer vs ExchangeRate-API
LearnReading source and market_session in your pipelineIndicative vs executable FX rates: what a rates API actually gives youECB reference rates, explained
Live RatesEUR/USDGBP/USDUSD/JPY