forked from alenthomas/json-parsing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
go.go
42 lines (32 loc) · 804 Bytes
/
go.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type jsonResponse struct {
Base string `json:"base"`
Date string `json:"date"`
Rates struct {
MYR float64 `json:"MYR"`
} `json:"rates"`
}
func main() {
symbols := "MYR"
base := "SGD"
// GET the JSON file
resp, err := http.Get(fmt.Sprintf("http://api.fixer.io/latest?symbols=%s&base=%s", symbols, base))
if err != nil {
log.Fatalln(err.Error())
}
defer resp.Body.Close()
b := &jsonResponse{}
// Read from http response body and decode it into jsonResponse struct
err = json.NewDecoder(resp.Body).Decode(b)
if err != nil {
log.Fatalln(err.Error())
}
// Only reason to dereference here is to not print a '&' symbol before the contents of struct
fmt.Printf("%s 1 = %s %f\n", base, symbols, b.Rates.MYR)
}