diff options
Diffstat (limited to 'web/cryptocompare/cryptocompare.go')
| -rw-r--r-- | web/cryptocompare/cryptocompare.go | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/web/cryptocompare/cryptocompare.go b/web/cryptocompare/cryptocompare.go new file mode 100644 index 0000000..6886f77 --- /dev/null +++ b/web/cryptocompare/cryptocompare.go @@ -0,0 +1,44 @@ +// Package cryptocompare fetches the latest USD price of a given crpytocurrency from CryptoCompare +package cryptocompare + +import ( + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + + "within.website/x/web" + _ "within.website/x/web/useragent" +) + +func Get(symbol string, currencies []string) (map[string]float64, error) { + u, err := url.Parse("https://min-api.cryptocompare.com/data/price") + if err != nil { + return nil, err + } + + q := u.Query() + q.Set("fsym", symbol) + q.Set("tsyms", strings.Join(currencies, ",")) + + u.RawQuery = q.Encode() + + resp, err := http.Get(u.String()) + if err != nil { + return nil, fmt.Errorf("cryptocompare: can't fetch result: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, web.NewError(http.StatusOK, resp) + } + + defer resp.Body.Close() + + result := make(map[string]float64) + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + return nil, fmt.Errorf("cryptocompare: can't decode result: %w") + } + + return result, nil +} |
