/
price_board.go
58 lines (45 loc) · 1.34 KB
/
price_board.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
package daos
import (
"fmt"
"github.com/tomochain/tomodex/errors"
"io/ioutil"
"log"
"net/http"
"github.com/tidwall/gjson"
"github.com/tomochain/tomodex/app"
)
type PriceBoardDao struct {
}
// NewTokenDao returns a new instance of TokenDao.
func NewPriceBoardDao() *PriceBoardDao {
return &PriceBoardDao{}
}
func (dao *PriceBoardDao) GetLatestQuotes() (map[string]float64, error) {
client := &http.Client{}
url := fmt.Sprintf("%s/cryptocurrency/quotes/latest?symbol=%s&convert=USD", app.Config.CoinmarketcapAPIUrl, app.Config.SupportedCurrencies)
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("X-CMC_PRO_API_KEY", app.Config.CoinmarketcapAPIKey)
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
return nil, err
}
status := gjson.Get(string(body), "status")
statusErrorCode := status.Get("error_code")
statusErrorMessage := status.Get("error_message")
if statusErrorCode.Int() != 0 {
logger.Error(statusErrorMessage.String())
return nil, errors.New(statusErrorMessage.String())
}
data := gjson.Get(string(body), "data")
result := make(map[string]float64)
data.ForEach(func(key, value gjson.Result) bool {
result[key.String()] = value.Get("quote.USD.price").Float()
return true // keep iterating
})
return result, nil
}