-
Notifications
You must be signed in to change notification settings - Fork 0
/
usd.go
executable file
·77 lines (68 loc) · 1.78 KB
/
usd.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
)
type Rates struct {
Base string `json:"base"`
Date string `json:"date"`
Currencies struct {
CNY float64 `json:"CNY"`
CAD float64 `json:"CAD"`
CHF float64 `json:"CHF"`
EUR float64 `json:"EUR"`
NZD float64 `json:"NZD"`
RUB float64 `json:"RUB"`
JPY float64 `json:"JPY"`
USD float64 `json:"USD"`
} `json:"rates"`
}
var (
current string
err error
rates Rates
response *http.Response
body []byte
)
func main() {
flag.Parse()
args := flag.Args()
if len(args) < 1 {
fmt.Println("Please specify start currency, e.g. 'go run currency.go USD' (Available values CNY/CAD/CHF/EUR/NZD/RUB/JPY/USD)")
os.Exit(1)
}
// Provide base currency
current = args[0]
// Use api.fixer.io to get a JSON response
response, err = http.Get("http://api.fixer.io/latest?base=" + current)
if err != nil {
fmt.Println(err)
}
defer response.Body.Close()
// Read the data into a byte slice(string)
body, err = ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
}
// Unmarshal the JSON byte slice to a predefined struct
err = json.Unmarshal(body, &rates)
if err != nil {
fmt.Println(err)
}
// Everything accessible in struct now
fmt.Println("\n==== Currency Rates ====\n")
fmt.Println("Base:\t", rates.Base)
fmt.Println("Date:\t", rates.Date)
fmt.Println("US Dollar:\t", rates.Currencies.USD)
fmt.Println("China Yuan:\t", rates.Currencies.CNY)
fmt.Println("Canadian Dollar:\t", rates.Currencies.CAD)
fmt.Println("Swiss Franc:\t", rates.Currencies.CHF)
fmt.Println("Euro:\t", rates.Currencies.EUR)
fmt.Println("Russian Ruble:\t", rates.Currencies.RUB)
fmt.Println("Japanese Yen:\t", rates.Currencies.JPY)
fmt.Println("New Zealand Dollar:\t", rates.Currencies.NZD)
}