converter/cmd/crypto.go

117 lines
2.6 KiB
Go
Raw Normal View History

2023-03-01 02:11:17 +00:00
/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/spf13/cobra"
)
2023-03-01 02:37:33 +00:00
type Search struct {
Coins []struct {
ID string `json:"id"`
Name string `json:"name"`
APISymbol string `json:"api_symbol"`
Symbol string `json:"symbol"`
MarketCapRank int `json:"market_cap_rank"`
Thumb string `json:"thumb"`
Large string `json:"large"`
} `json:"coins"`
2023-03-01 02:11:17 +00:00
}
type Price map[string]USD
type USD struct {
Usd float64
}
var (
price_url = "https://api.coingecko.com/api/v3/simple/price?"
2023-03-01 02:37:33 +00:00
search_url = "https://api.coingecko.com/api/v3/search?query="
2023-03-01 02:11:17 +00:00
)
var amount float64
// cryptoCmd represents the crypto command
var cryptoCmd = &cobra.Command{
Use: "crypto",
Short: "get price of token",
Long: `get price of token`,
2023-03-01 02:37:33 +00:00
Args: cobra.MatchAll(cobra.RangeArgs(1, 2), cobra.OnlyValidArgs),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) >= 2 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return getTokens(toComplete), cobra.ShellCompDirectiveNoFileComp
},
2023-03-01 02:11:17 +00:00
RunE: func(cmd *cobra.Command, args []string) error {
price, err := usdPrice(args[0])
if err != nil {
return err
}
price = price * amount
price2 := float64(1)
if len(args) >= 2 {
price2, err = usdPrice(args[1])
if err != nil {
return err
}
}
fmt.Println(price / price2)
return nil
},
}
2023-03-01 02:37:33 +00:00
func getTokens(in string) []string {
if in == "" {
return []string{"ethereum", "bitcoin", "tether", "binancecoin", "usd-coin", "ripple", "cardano", "dogecoin", "matic-network"}
}
resp, err := http.Get(search_url + in)
if err != nil {
return []string{err.Error()}
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return []string{err.Error()}
}
var tokens Search
err = json.Unmarshal(body, &tokens)
if err != nil {
return []string{err.Error()}
}
out := []string{}
for _, token := range tokens.Coins {
out = append(out, token.ID)
}
return out
}
2023-03-01 02:11:17 +00:00
func usdPrice(token string) (float64, error) {
resp, err := http.Get(price_url + fmt.Sprintf("ids=%s&vs_currencies=usd", token))
if err != nil {
return 0, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, err
}
var price Price
err = json.Unmarshal(body, &price)
if err != nil {
return 0, err
}
return price[token].Usd, nil
}
func init() {
rootCmd.AddCommand(cryptoCmd)
cryptoCmd.PersistentFlags().Float64VarP(&amount, "amount", "a", 1, "amount of the given token")
}