-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathto_usd.go
52 lines (43 loc) · 1.29 KB
/
to_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
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
)
// convert crypto to usd via Kraken API
func toUSD(value float64, currency string) (map[string]interface{}, error) {
if currency == "credits" {
return map[string]interface{}{"currentprice": nil, "converted": "N/A"}, nil
}
url := fmt.Sprintf("https://api.kraken.com/0/public/Ticker?pair=%susd", currency)
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("failed to send request: %v", err)
}
defer resp.Body.Close()
var response struct {
Result map[string]struct {
A []string `json:"a"`
} `json:"result"`
}
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return nil, fmt.Errorf("failed to decode response: %v", err)
}
var currentPrice string
switch strings.ToUpper(currency) {
case "BTC":
currentPrice = response.Result["XXBTZUSD"].A[0]
case "XMR":
currentPrice = response.Result["XXMRZUSD"].A[0]
case "LTC":
currentPrice = response.Result["XLTCZUSD"].A[0]
}
currentPriceFloat, err := strconv.ParseFloat(currentPrice, 64)
if err != nil {
return nil, fmt.Errorf("failed to parse current price: %v", err)
}
converted := fmt.Sprintf("$%.3f", value*currentPriceFloat)
return map[string]interface{}{"currentprice": currentPrice, "converted": converted}, nil
}