Home > Back-end >  How to get simple data from API call for further evaluation in Golang
How to get simple data from API call for further evaluation in Golang

Time:06-10

I try to get Data from a Response, how can I get a simple call and output afterwards e.g. the rate like fmt.Println(rate) which should result in 1.170228

// Response
{
    "rates":{
        "EURUSD":{
            "rate":1.170228,
            "timestamp":1532428704963}
        },
    "code":200
}

// Request https://www.freeforexapi.com/api/live?pairs=EURUSD

CodePudding user response:

Use the http package to get the resource, decode the JSON response to Go values, access the rate field:

r, err := http.Get("https://www.freeforexapi.com/api/live?pairs=EURUSD")
if err != nil {
    log.Fatal(err)                                                 
}                                                         
defer r.Body.Close()
if r.StatusCode != 200 {
    log.Fatalf("status = %v", r.StatusCode)
}
var v struct {
    Code  int
    Rates map[string]struct{ Rate float64 }
}
if err := json.NewDecoder(r.Body).Decode(&v); err != nil {
    log.Fatal(err)
}
fmt.Println(v.Rates["EURUSD"].Rate)
  • Related