---
title: "Live gold prices in Go · goldprice.dev"
description: "Call goldprice.dev from Go with net/http, shopspring/decimal, retry-on-429, and a 60-second TTL cache. Free tier: 5,000 calls/mo. Tested June 2026."
canonical: "https://goldprice.dev/tutorials/go"
---

# How to get live gold prices in Go

Call the goldprice.dev API from Go with net/http, shopspring/decimal, retry-on-429, and a 60-second TTL cache.

26 Jun 2026 · 4 min read

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](https://goldprice.dev/onboarding). After email confirmation, your dashboard shows a key starting with `ga_live_`. Set it as an environment variable:

```bash
export GOLDPRICE_API_KEY=ga_live_replace_with_your_key_here
```

The 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:

```bash
go mod init goldprice-demo
go get github.com/shopspring/decimal
```

## Write 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 title="goldprice.go"
// go: goldprice.go
// curl-equivalent: https://api.goldprice.dev/v1/spot/XAU-USD-SPOT
package main

import (
	"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.

```bash
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.

```go title="goldprice.go · multi-currency"
c := NewClient()

// USD spot, default
c.Spot("XAU-USD-SPOT")

c.Spot("XAU-INR-SPOT")

c.Spot("XAU-EUR-SPOT")

// Silver in USD
c.Spot("XAG-USD-SPOT")
```

## Expected output

```json
{
  "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](https://goldprice.dev/onboarding). `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](https://goldprice.dev/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.Context` parameter to `Spot()` and use `http.NewRequestWithContext` so callers can set deadlines and cancellation
- Collapse duplicate in-flight requests with `golang.org/x/sync/singleflight` so 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

## Questions

### How often does the price update?

The spot endpoint refreshes every 60 seconds (live spot data; Free/keyless delayed 15 minutes, paid live). The 60-second TTL above matches that cadence, repeated Spot() calls within the window return the cached struct without an HTTP round-trip.

### Will this fit the free tier with auto-refresh?

It depends on your call site. A service polling once per minute = 1,440 calls/day = ~43,000/month, well over the 5,000/month free tier. Cache aggressively and call only on demand. Polling once per hour = ~720/month, inside the free tier. For continuous high-volume use, see /pricing for paid plans.

### Can I use this commercially?

Commercial use is allowed on every plan. Paid plans need no credit link; Free requires a visible link to goldprice.dev near the prices.

### Why decimal.Decimal instead of float64?

Float arithmetic drifts on summation: 0.1 + 0.2 is 0.30000000000000004 in IEEE-754. Gold prices carry 2 decimal places; summing thousands of values in float64 introduces basis-point errors over time. decimal.Decimal keeps exact arithmetic, and the API returns prices as strings precisely so clients can decode them without loss.

### Is the client safe for concurrent goroutines?

Yes. The cache map is guarded by a sync.Mutex, so multiple goroutines can call Spot() on the same Client. For high concurrency on the same cold symbol, add a singleflight.Group so only one goroutine performs the fetch while the others wait for its result.

### What metals are supported?

Gold (XAU), silver (XAG), copper (HG), platinum and palladium are not offered on any tier. Substitute the metal code in the symbol, e.g. c.Spot("XAG-USD-SPOT").

### Can I have Claude write this for me?

Yes. Open Claude Desktop with the goldprice.dev MCP server installed and ask: Build a Go client for the goldprice.dev /v1/spot endpoint. Use net/http, shopspring/decimal, a 60-second per-symbol cache behind a mutex, and retry-on-429 with exponential backoff. Read the API key from GOLDPRICE_API_KEY. The MCP server gives Claude the live schema, so generated code uses correct field names and tags on the first try.

## Keep reading

- [Python logo How to get live gold prices in Python](https://goldprice.dev/tutorials/python)
- [PHP logo How to get live gold prices in PHP](https://goldprice.dev/tutorials/php)
- [n8n logo How to get live gold prices in n8n](https://goldprice.dev/tutorials/n8n)

Source: https://goldprice.dev/tutorials/go
