converter/cmd/currency.go

241 lines
2.8 KiB
Go
Raw Normal View History

2023-03-01 01:39:42 +00:00
/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"github.com/spf13/cobra"
)
var currencies = []string{
"USD",
"AED",
"AFN",
"ALL",
"AMD",
"ANG",
"AOA",
"ARS",
"AUD",
"AWG",
"AZN",
"BAM",
"BBD",
"BDT",
"BGN",
"BHD",
"BIF",
"BMD",
"BND",
"BOB",
"BRL",
"BSD",
"BTN",
"BWP",
"BYN",
"BZD",
"CAD",
"CDF",
"CHF",
"CLP",
"CNY",
"COP",
"CRC",
"CUP",
"CVE",
"CZK",
"DJF",
"DKK",
"DOP",
"DZD",
"EGP",
"ERN",
"ETB",
"EUR",
"FJD",
"FKP",
"FOK",
"GBP",
"GEL",
"GGP",
"GHS",
"GIP",
"GMD",
"GNF",
"GTQ",
"GYD",
"HKD",
"HNL",
"HRK",
"HTG",
"HUF",
"IDR",
"ILS",
"IMP",
"INR",
"IQD",
"IRR",
"ISK",
"JEP",
"JMD",
"JOD",
"JPY",
"KES",
"KGS",
"KHR",
"KID",
"KMF",
"KRW",
"KWD",
"KYD",
"KZT",
"LAK",
"LBP",
"LKR",
"LRD",
"LSL",
"LYD",
"MAD",
"MDL",
"MGA",
"MKD",
"MMK",
"MNT",
"MOP",
"MRU",
"MUR",
"MVR",
"MWK",
"MXN",
"MYR",
"MZN",
"NAD",
"NGN",
"NIO",
"NOK",
"NPR",
"NZD",
"OMR",
"PAB",
"PEN",
"PGK",
"PHP",
"PKR",
"PLN",
"PYG",
"QAR",
"RON",
"RSD",
"RUB",
"RWF",
"SAR",
"SBD",
"SCR",
"SDG",
"SEK",
"SGD",
"SHP",
"SLE",
"SLL",
"SOS",
"SRD",
"SSP",
"STN",
"SYP",
"SZL",
"THB",
"TJS",
"TMT",
"TND",
"TOP",
"TRY",
"TTD",
"TVD",
"TWD",
"TZS",
"UAH",
"UGX",
"UYU",
"UZS",
"VES",
"VND",
"VUV",
"WST",
"XAF",
"XCD",
"XDR",
"XOF",
"XPF",
"YER",
"ZAR",
"ZMW",
"ZWL",
}
var api_url = "https://open.er-api.com/v6/latest/"
type Response struct {
Rates map[string]float64
}
// unitsCmd represents the units command
var currencyCmd = &cobra.Command{
Use: "currency",
Aliases: []string{"c", "money"},
Short: "converts money",
Long: `converts monee`,
Args: cobra.MatchAll(cobra.ExactArgs(3), cobra.OnlyValidArgs),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) >= 2 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return getCurrencyNames(toComplete), cobra.ShellCompDirectiveNoFileComp
},
RunE: func(cmd *cobra.Command, args []string) error {
currencyFrom := args[0]
currencyTo := args[1]
amount, err := strconv.ParseFloat(args[2], 64)
if err != nil {
return err
}
res, err := http.Get(api_url + currencyFrom)
if err != nil {
return err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return err
}
var response Response
json.Unmarshal(body, &response)
fmt.Println(response.Rates[currencyTo] * amount)
return nil
},
}
func getCurrencyNames(in string) []string {
out := []string{}
for _, name := range currencies {
if in == "" {
out = append(out, name)
} else {
if strings.HasPrefix(name, in) {
out = append(out, name)
}
}
}
return out
}
func init() {
rootCmd.AddCommand(currencyCmd)
}