2021-10-23 19:48:50 +02:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
2021-10-23 20:32:26 +02:00
|
|
|
"strings"
|
2021-10-23 19:48:50 +02:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
type currencyResponse struct {
|
2021-10-23 20:32:26 +02:00
|
|
|
Amount int `json:"amount"`
|
|
|
|
Base string `json:"base"`
|
|
|
|
Rates map[string]float32 `json:"rates"`
|
2021-10-23 19:48:50 +02:00
|
|
|
}
|
|
|
|
|
2021-10-23 20:43:39 +02:00
|
|
|
// Currency returns the exchange rate for a given given amount to another.
|
2021-10-23 19:48:50 +02:00
|
|
|
func Currency(currAmount string, currFrom string, currTo string) (string, error) {
|
|
|
|
baseUrl := "https://api.frankfurter.app"
|
2021-10-23 20:40:40 +02:00
|
|
|
currFromUpper := strings.ToUpper(currFrom)
|
|
|
|
currToUpper := strings.ToUpper(currTo)
|
|
|
|
|
2021-10-23 22:52:10 +02:00
|
|
|
// https://api.frankfurter.app/latest?amount=10&from=gbp&to=usd
|
2021-10-23 20:40:40 +02:00
|
|
|
response, err := http.Get(fmt.Sprintf("%s/latest?amount=%s&from=%s&to=%s", baseUrl, currAmount, currFromUpper, currToUpper))
|
2021-10-23 19:48:50 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Error(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
responseData, err := ioutil.ReadAll(response.Body)
|
|
|
|
if err != nil {
|
|
|
|
log.Error(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var responseObject currencyResponse
|
|
|
|
json.Unmarshal(responseData, &responseObject)
|
|
|
|
|
2021-10-23 20:32:26 +02:00
|
|
|
// log.Info(responseObject.Amount)
|
|
|
|
// log.Info(responseObject.Base)
|
|
|
|
// log.Info(responseObject.Rates[strings.ToUpper(currTo)])
|
2021-10-23 20:40:40 +02:00
|
|
|
|
|
|
|
if responseObject.Rates[currToUpper] != 0 {
|
|
|
|
return fmt.Sprintf("%s %s = %.2f %s", currAmount, currFromUpper, responseObject.Rates[currToUpper], currToUpper), nil
|
2021-10-23 20:32:26 +02:00
|
|
|
}
|
2021-10-23 22:52:10 +02:00
|
|
|
|
2021-10-23 20:32:26 +02:00
|
|
|
return "Something went wrong FeelsBadMan", nil
|
2021-10-23 19:48:50 +02:00
|
|
|
}
|