To get live gold prices in Go, send a GET to api.goldprice.dev/v1/spot/XAU-USD-SPOT with your API key in the X-API-Key header using net/http. Decode the JSON into a struct, parse prices with shopspring/decimal for exact math, and cache per symbol for 60 seconds. The free tier covers 5,000 calls/month, no credit card. Tested June 2026 against Go 1.23.
Get your goldprice.dev API key
Sign up for a free account at goldprice.dev/onboarding. After email confirmation, your dashboard shows a key starting with ga_live_. Set it as an environment variable:
export GOLDPRICE_API_KEY=ga_live_replace_with_your_key_hereThe free tier includes 5,000 calls/month and gold spot in 31 currencies. No credit card required.
Initialise the module and add the decimal dependency
The standard library covers the HTTP call and JSON decode. The one external package is shopspring/decimal, so price math stays exact instead of drifting on float64. Create a module and add it:
go mod init goldprice-demogo get github.com/shopspring/decimalWrite the goldprice client
Save this as goldprice.go. The Spot() method caches per symbol for 60 seconds behind a mutex, retries up to 3 times on 429 with exponential backoff, and decodes prices straight into decimal.Decimal (its UnmarshalJSON accepts the string prices the API returns).
// go: goldprice.go// curl-equivalent: https://api.goldprice.dev/v1/spot/XAU-USD-SPOTpackage mainimport ( "encoding/json" "errors" "fmt" "net/http" "os" "sync" "time" "github.com/shopspring/decimal")const ( apiBase = "https://api.goldprice.dev" timeout = 5 * time.Second ttl = 60 * time.Second)// SpotResponse holds the fields we consume from /v1/spot/{symbol}.type SpotResponse struct { Symbol string `json:"symbol"` QuoteCurrency string `json:"quote_currency"` Price decimal.Decimal `json:"price"` Bid decimal.Decimal `json:"bid"` Ask decimal.Decimal `json:"ask"` IsStale bool `json:"is_stale"` ComputedAt string `json:"computed_at"`}var errRateLimited = errors.New("goldprice: 429 rate limited")type cacheEntry struct { resp SpotResponse expires time.Time}// Client is safe for concurrent use.type Client struct { apiKey string http *http.Client mu sync.Mutex cache map[string]cacheEntry}func NewClient() *Client { key := os.Getenv("GOLDPRICE_API_KEY") if key == "" { panic("GOLDPRICE_API_KEY not set") } return &Client{ apiKey: key, http: &http.Client{Timeout: timeout}, cache: make(map[string]cacheEntry), }}// Spot fetches the live spot price. Cached 60s per symbol, retries 3x on 429.func (c *Client) Spot(symbol string) (SpotResponse, error) { c.mu.Lock() if e, ok := c.cache[symbol]; ok && time.Now().Before(e.expires) { c.mu.Unlock() return e.resp, nil } c.mu.Unlock() var out SpotResponse var err error for attempt := 0; attempt < 3; attempt++ { out, err = c.fetch(symbol) if err == nil { c.mu.Lock() c.cache[symbol] = cacheEntry{resp: out, expires: time.Now().Add(ttl)} c.mu.Unlock() return out, nil } if !errors.Is(err, errRateLimited) { return SpotResponse{}, err } time.Sleep(time.Duration(1<<attempt) * time.Second) // 1s, 2s, 4s } return SpotResponse{}, err}func (c *Client) fetch(symbol string) (SpotResponse, error) { req, err := http.NewRequest(http.MethodGet, apiBase+"/v1/spot/"+symbol, nil) if err != nil { return SpotResponse{}, err } req.Header.Set("X-API-Key", c.apiKey) resp, err := c.http.Do(req) if err != nil { return SpotResponse{}, err } defer resp.Body.Close() if resp.StatusCode == http.StatusTooManyRequests { return SpotResponse{}, errRateLimited } if resp.StatusCode != http.StatusOK { return SpotResponse{}, fmt.Errorf("goldprice: unexpected status %d", resp.StatusCode) } var out SpotResponse if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { return SpotResponse{}, err } return out, nil}func main() { c := NewClient() r, err := c.Spot("XAU-USD-SPOT") if err != nil { panic(err) } fmt.Printf("%s-%s: %s (computed %s)\n", r.Symbol, r.QuoteCurrency, r.Price, r.ComputedAt)}Run it
From the same shell where you exported GOLDPRICE_API_KEY, run the file. The first call hits the API; calls within 60 seconds return the cached value without a round-trip. A fresh process starts with an empty cache (in-process only), back it with Redis if you need cross-process sharing.
go run goldprice.go# XAU-USD: 4012.75 (computed 2026-10-23T07:00:18.221118+00:00)Switch currency or metal
Symbols are METAL-CURRENCY-SPOT. Pass any of the 31 spot currencies to Spot(). Each unique symbol caches independently behind the mutex, so a dashboard polling 5 symbols at 60-second intervals fires 5 uncached calls per minute and 0 cached.
c := NewClient()// USD spot, defaultc.Spot("XAU-USD-SPOT")c.Spot("XAU-INR-SPOT")c.Spot("XAU-EUR-SPOT")// Silver in USDc.Spot("XAG-USD-SPOT")Expected output
{ "symbol": "XAU", "quote_currency": "USD", "unit": "troy_ounce", "contract_type": "spot", "price": "4012.75", "is_stale": false, "computed_at": "2026-10-23T07:00:18.221118+00:00"}Stdout shows one line: symbol, quote currency, the price as a decimal.Decimal, and the ISO 8601 ComputedAt timestamp. The SpotResponse struct is what your downstream code consumes.
Common errors
| Code | What you see | Fix |
|---|---|---|
| 401 | goldprice: unexpected status 401 on the first call | API key missing or invalid. Confirm the variable is set: echo $GOLDPRICE_API_KEY. If empty, re-export from your dashboard. NewClient() panics at construction when the env var is empty, so the failure surfaces immediately rather than mid-request. |
| 429 | Three retries with backoff all return 429, then Spot returns the rate-limit error | You hit the per-minute cap. The 60-second cache prevents this for steady polling; if a burst of distinct symbols arrives at once, stagger the calls or add a golang.org/x/sync/singleflight group to collapse duplicate in-flight requests. For sustained volume, see /pricing for paid plans. |
| N/A | price decodes as 0 or the build complains about the decimal type | The API sends prices as JSON strings (e.g. "4012.75"). decimal.Decimal from shopspring/decimal unmarshals strings correctly; a plain float64 field would lose precision and a custom int type would fail to decode. Keep the field typed as decimal.Decimal and run go mod tidy if the import is unresolved. |
Going further
- Add a
context.Contextparameter toSpot()and usehttp.NewRequestWithContextso callers can set deadlines and cancellation - Collapse duplicate in-flight requests with
golang.org/x/sync/singleflightso a thundering herd on one symbol makes a single API call - Add a
Bars()method for/v1/bars?symbol=XAU-USD-SPOT&interval=1d&from=...&to=...and feed the rows into a backtest - Back the cache with Redis so a fleet of pods shares one warm price instead of each holding its own
- Expose Prometheus counters for cache hit rate, request latency, and 429-retry totals