aboutsummaryrefslogtreecommitdiff
path: root/web/cryptocompare
diff options
context:
space:
mode:
authorXe Iaso <me@xeiaso.net>2023-03-05 16:23:33 -0500
committerXe Iaso <me@xeiaso.net>2023-03-05 16:23:33 -0500
commitb29f4583327c98a18eaebd98ccd6d416504128e4 (patch)
tree69daf2121b8ca2e70508c650aa74c78192648a60 /web/cryptocompare
parentea95496b1d9c9637bad0159b04e781daab359f1d (diff)
downloadx-b29f4583327c98a18eaebd98ccd6d416504128e4.tar.xz
x-b29f4583327c98a18eaebd98ccd6d416504128e4.zip
add cryptocompare API bindings
Signed-off-by: Xe Iaso <me@xeiaso.net>
Diffstat (limited to 'web/cryptocompare')
-rw-r--r--web/cryptocompare/cryptocompare.go44
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
+}