Skip to content

Instantly share code, notes, and snippets.

@samredai
Created September 26, 2021 19:48
Show Gist options
  • Save samredai/af9f4b206cd10923dfb74ad2e86a578b to your computer and use it in GitHub Desktop.
Save samredai/af9f4b206cd10923dfb74ad2e86a578b to your computer and use it in GitHub Desktop.
Go: Query a REST API and convert the JSON payload to a struct
package main
import (
"encoding/json"
"net/http"
"fmt"
)
// 20210926113330
// https://api.coindesk.com/v1/bpi/currentprice.json
// API Response Body
// {
// "time": {
// "updated": "Sep 26, 2021 15:33:00 UTC",
// "updatedISO": "2021-09-26T15:33:00+00:00",
// "updateduk": "Sep 26, 2021 at 16:33 BST"
// },
// "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
// "chartName": "Bitcoin",
// "bpi": {
// "USD": {
// "code": "USD",
// "symbol": "$",
// "rate": "43,327.2067",
// "description": "United States Dollar",
// "rate_float": 43327.2067
// },
// "GBP": {
// "code": "GBP",
// "symbol": "£",
// "rate": "31,660.3597",
// "description": "British Pound Sterling",
// "rate_float": 31660.3597
// },
// "EUR": {
// "code": "EUR",
// "symbol": "€",
// "rate": "36,968.2892",
// "description": "Euro",
// "rate_float": 36968.2892
// }
// }
// }
type Time struct {
Updated string `json:updated`
UpdatedISO string `json:updatedISO`
Updateduk string `json:updateduk`
}
type CUR struct {
Code string `json:code`
Symbol string `json:symbol`
Rate string `json:rate`
Description string `json:description`
Rate_float float32 `json:rate_float`
}
type BPI struct {
USD CUR
GBP CUR
EUR CUR
}
type Response struct {
Time Time `json:time`
ChartName string `json:chartName`
Disclaimer string `json:disclaimer`
Bpi BPI `json:bpi`
}
func main() {
resp, err := http.Get("https://api.coindesk.com/v1/bpi/currentprice.json")
if err != nil {
panic(err)
}
defer resp.Body.Close()
var r Response
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
panic(err)
}
fmt.Printf("r.Time.Updated: %s\n", r.Time.Updated)
fmt.Printf("r.Time.UpdatedISO: %s\n", r.Time.UpdatedISO)
fmt.Printf("r.Time.Updateduk: %s\n", r.Time.Updateduk)
fmt.Printf("r.ChartName: %s\n", r.ChartName)
fmt.Printf("r.Disclaimer: %s\n", r.Disclaimer)
fmt.Printf("r.Bpi.USD: %s\n", r.Bpi.USD)
fmt.Printf("r.Bpi.GBP: %s\n", r.Bpi.GBP)
fmt.Printf("r.Bpi.EUR: %s\n", r.Bpi.EUR)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment