-
Notifications
You must be signed in to change notification settings - Fork 2
/
convert.go
62 lines (49 loc) · 1.31 KB
/
convert.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
package goforex
import (
"errors"
"strconv"
"strings"
)
type Convert struct {
From string `json:"from"`
To string `json:"to"`
Amount float64 `json:"amount,string"`
Result float64 `json:"result,string"`
}
func (c *Client) Convert(params ...map[string]string) (Convert, error) {
var convert Convert
if len(params) < 1 {
err := errors.New("missing parameters")
return convert, err
}
switch {
case params[0]["from"] == "":
err := errors.New("missing 'from' parameter")
return convert, err
case params[0]["to"] == "":
err := errors.New("missing 'to' parameter")
return convert, err
case params[0]["amount"] == "":
err := errors.New("missing 'amount' parameter")
return convert, err
}
amount, err := strconv.ParseFloat(params[0]["amount"], 64)
if err != nil {
return convert, err
}
convert.From = strings.ToUpper(params[0]["from"])
convert.To = strings.ToUpper(params[0]["to"])
convert.Amount = amount
p := map[string]string{"base": convert.From, "symbols": convert.To}
rates, err := c.Latest(p)
if err != nil {
return convert, err
}
rateInt, rateDp := Ftoi(rates.Rates[strings.ToUpper(convert.To)])
amountInt, amountDp := Ftoi(convert.Amount)
resultInt := rateInt * amountInt
dp := rateDp + amountDp
result := Itof(resultInt, dp)
convert.Result = result
return convert, nil
}