crypto
This commit is contained in:
parent
08a0b2c078
commit
af3ceec223
@ -12,10 +12,16 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
type Tokens []struct {
|
||||
ID string `json:"id"`
|
||||
Symbol string `json:"symbol"`
|
||||
Name string `json:"name"`
|
||||
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"`
|
||||
}
|
||||
|
||||
type Price map[string]USD
|
||||
@ -26,8 +32,7 @@ type USD struct {
|
||||
|
||||
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"
|
||||
search_url = "https://api.coingecko.com/api/v3/search?query="
|
||||
)
|
||||
|
||||
var amount float64
|
||||
@ -37,6 +42,13 @@ var cryptoCmd = &cobra.Command{
|
||||
Use: "crypto",
|
||||
Short: "get price of token",
|
||||
Long: `get price of token`,
|
||||
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
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
price, err := usdPrice(args[0])
|
||||
if err != nil {
|
||||
@ -55,6 +67,31 @@ var cryptoCmd = &cobra.Command{
|
||||
},
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func usdPrice(token string) (float64, error) {
|
||||
resp, err := http.Get(price_url + fmt.Sprintf("ids=%s&vs_currencies=usd", token))
|
||||
if err != nil {
|
||||
|
Loading…
Reference in New Issue
Block a user