plugins/coingecko/http.go (view raw)
1package coingecko
2
3import (
4 "encoding/json"
5 "net/http"
6 "net/url"
7 "time"
8)
9
10var (
11 CoinGeckoClient = &http.Client{
12 Timeout: 10 * time.Second,
13 }
14 apiEndpoint = "https://api.coingecko.com/api/v3/coins"
15)
16
17type CoinId struct {
18 Id string `json:"id"`
19 Symbol string `json:"symbol"`
20}
21
22type CoinData struct {
23 Name string `json:"name"`
24 Symbol string `json:"symbol"`
25 MarketData struct {
26 Current struct {
27 Usd float64 `json:"usd"`
28 } `json:"current_price"`
29 High struct {
30 Usd float64 `json:"usd"`
31 } `json:"high_24h"`
32 Low struct {
33 Usd float64 `json:"usd"`
34 } `json:"low_24h"`
35 MarketCap struct {
36 Usd float64 `json:"usd"`
37 } `json:"market_cap"`
38 MarketCapRank int64 `json:"market_cap_rank"`
39 Change24h float64 `json:"price_change_percentage_24h"`
40 Change7d float64 `json:"price_change_percentage_7d"`
41 Change14d float64 `json:"price_change_percentage_14d"`
42 Change30d float64 `json:"price_change_percentage_30d"`
43 Change60d float64 `json:"price_change_percentage_60d"`
44 Change200d float64 `json:"price_change_percentage_200d"`
45 Change1y float64 `json:"price_change_percentage_1y"`
46 } `json:"market_data"`
47}
48
49func GetCoinList() ([]CoinId, error) {
50 req, err := http.NewRequest("GET", apiEndpoint+"/list", nil)
51 if err != nil {
52 return nil, err
53 }
54 req.Header.Add("User-Agent", "github.com/icyphox/paprika")
55
56 res, err := CoinGeckoClient.Do(req)
57 if err != nil {
58 return nil, err
59 }
60 defer res.Body.Close()
61
62 var resData []CoinId
63 err = json.NewDecoder(res.Body).Decode(&resData)
64 if err != nil {
65 return nil, err
66 }
67
68 return resData, nil
69}
70
71func GetCoinPrice(coinId string) (*CoinData, error) {
72 cid := url.PathEscape(coinId)
73 req, err := http.NewRequest("GET", apiEndpoint+"/"+cid, nil)
74 if err != nil {
75 return nil, err
76 }
77 req.Header.Add("User-Agent", "github.com/icyphox/paprika")
78
79 res, err := CoinGeckoClient.Do(req)
80 if err != nil {
81 return nil, err
82 }
83 defer res.Body.Close()
84
85 if res.StatusCode == 404 {
86 return nil, nil
87 }
88
89 var resData *CoinData
90 err = json.NewDecoder(res.Body).Decode(&resData)
91 if err != nil {
92 return nil, err
93 }
94
95 return resData, nil
96}