goCake/coinGeckoAPI.go

56 lines
1.5 KiB
Go
Raw Normal View History

package main
import (
"encoding/json"
"fmt"
"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
readBody(response, &status)
if status.GeckoSays == "(V3) To the Moon!" {
// API is working as expected
return true
}
}
return false
}
// 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")
}
func readBody(h *http.Response, i interface{}) {
// API is available, let's read the response
data, _ := ioutil.ReadAll(h.Body)
json.Unmarshal(data, i)
}