This commit is contained in:
abs3nt 2023-02-28 18:11:17 -08:00
parent d72b28198a
commit 08a0b2c078

79
cmd/crypto.go Normal file
View File

@ -0,0 +1,79 @@
/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/spf13/cobra"
)
type Tokens []struct {
ID string `json:"id"`
Symbol string `json:"symbol"`
Name string `json:"name"`
}
type Price map[string]USD
type USD struct {
Usd float64
}
var (
price_url = "https://api.coingecko.com/api/v3/simple/price?"
vs_url = "https://api.coingecko.com/api/v3/simple/supported_vs_currencies"
tokens_url = "https://api.coingecko.com/api/v3/coins/list"
)
var amount float64
// cryptoCmd represents the crypto command
var cryptoCmd = &cobra.Command{
Use: "crypto",
Short: "get price of token",
Long: `get price of token`,
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
},
}
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")
}