How to get live (spot) gold price using API in Go?

< Back to Blog

Go is a statically typed, compiled programming language. This tutorial is a how to get live gold price using Go programming language.

Instructions

  1. Get a free API to use by signing up at Metalpriceapi.com and replace REPLACE_ME with your API key.
  2. Update base value to a currency or remove this query param.
  3. Update currencies value to a list of values or remove this query param. In the example below, you will get precious metal rates for gold, silver, palladium, and platinum.

For 2 and 3, you can find this documented at Offical Documentation

 

Fetch live gold price in Go

package main

import (
  "fmt"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "https://api.metalpriceapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=XAU,XAG,EUR"
  method := "GET"

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, nil)

  if err != nil {
    fmt.Println(err)
    return
  }
  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}