2020-11-21 14:06:58 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2020-11-21 17:36:33 +00:00
|
|
|
"fmt"
|
2020-11-21 14:06:58 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
// CheckStatusCoinGecko needs a comment
|
|
|
|
func CheckStatusCoinGecko() bool {
|
|
|
|
// needed answer for Coingecko API
|
|
|
|
type statusResponse struct {
|
|
|
|
GeckoSays string `json:"gecko_says"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// see if API is available
|
|
|
|
url := "https://api.coingecko.com/api/v3/ping"
|
|
|
|
response, err := http.Get(url)
|
|
|
|
if err == nil {
|
|
|
|
var status statusResponse
|
2020-11-21 17:36:33 +00:00
|
|
|
readBody(response, &status)
|
2020-11-21 14:06:58 +00:00
|
|
|
if status.GeckoSays == "(V3) To the Moon!" {
|
|
|
|
// API is working as expected
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-11-21 17:36:33 +00:00
|
|
|
// GetCoinValue needs a comment
|
|
|
|
func GetCoinValue(coinID string, fiat string) (float64, error) {
|
|
|
|
// check if API is up
|
|
|
|
if CheckStatusCoinGecko() == true {
|
|
|
|
// https://api.coingecko.com/api/v3/simple/price?ids=defichain&vs_currencies=eur
|
|
|
|
url := "https://api.coingecko.com/api/v3/simple/price?ids=" + coinID + "&vs_currencies=" + fiat
|
|
|
|
response, err := http.Get(url)
|
|
|
|
if err == nil {
|
|
|
|
// there's no error, we got a response
|
|
|
|
var r map[string]interface{}
|
|
|
|
readBody(response, &r)
|
|
|
|
// as the response will vary on coin and fiat we need to use interface{} here
|
|
|
|
value := r[coinID].(map[string]interface{})
|
|
|
|
return value[fiat].(float64), nil
|
|
|
|
}
|
|
|
|
return 0, fmt.Errorf("There was a problem with the response from Coingecko, Error is: %s", err.Error())
|
|
|
|
}
|
|
|
|
return 0, fmt.Errorf("The API of Coingecko seems to be down")
|
|
|
|
}
|
2020-11-21 14:06:58 +00:00
|
|
|
|
2020-11-21 17:36:33 +00:00
|
|
|
func readBody(h *http.Response, i interface{}) {
|
|
|
|
// API is available, let's read the response
|
|
|
|
data, _ := ioutil.ReadAll(h.Body)
|
|
|
|
json.Unmarshal(data, i)
|
2020-11-21 14:06:58 +00:00
|
|
|
}
|