-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
89 lines (75 loc) · 1.88 KB
/
main.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
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
rate, err := QueryExchangeRate("GBP", "USD")
if err != nil {
panic(err)
}
fmt.Println(rate)
}
type exchangeRateRequest struct {
Amount float64 `json:"amount"`
From string `json:"from"`
To string `json:"to"`
DecimalPoints int `json:"decimalPoints"`
CacheTime string `json:"cacheTime"`
Exchanger []exchange `json:"exchanger"`
}
type exchange struct {
Name string `json:"name"`
}
type exchangeRateResposne struct {
From string `json:"from"`
To string `json:"to"`
ExchangerName string `json:"exchangerName"`
ExchangeValue float64 `json:"exchangeValue"`
OriginalAmount float64 `json:"originalAmount"`
ConvertedAmount float64 `json:"convertedAmount"`
ConvertedText string `json:"convertedText"`
RateDateTime string `json:"rateDateTime"`
RateFromCache bool `json:"rateFromCache"`
}
func QueryExchangeRate(from, to string) (float64, error) {
url := "https://go-swap-server.herokuapp.com/convert"
req := &exchangeRateRequest{
Amount: 1,
From: from,
To: to,
DecimalPoints: 4,
CacheTime: "120s",
Exchanger: []exchange{
{Name: "yahoo"},
{Name: "google"},
},
}
query, err := json.Marshal(req)
if err != nil {
return 0, err
}
httpReq, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(query))
if err != nil {
return 0, err
}
httpReq.Header.Set("Content-Type", "application/json")
client := &http.Client{}
httpResp, err := client.Do(httpReq)
if err != nil {
return 0, err
}
defer httpResp.Body.Close()
body, err := ioutil.ReadAll(httpResp.Body)
if err != nil {
return 0, err
}
var resp exchangeRateResposne
if err := json.Unmarshal(body, &resp); err != nil {
return 0, err
}
return resp.ConvertedAmount, nil
}