Hey there, fellow Go enthusiast! Ready to dive into the world of cryptocurrency data? Let's build a slick CoinMarketCap API integration using the awesome go-coinmarketcap package. Buckle up, and let's get coding!
Before we jump in, make sure you've got:
First things first, let's create a new Go module:
mkdir cmc-integration && cd cmc-integration go mod init github.com/yourusername/cmc-integration
Now, let's install the go-coinmarketcap package:
go get github.com/miguelmota/go-coinmarketcap/pro/v1
Time to write some Go! Create a main.go
file and let's get that client up and running:
package main import ( "fmt" "log" cmc "github.com/miguelmota/go-coinmarketcap/pro/v1" ) func main() { client := cmc.NewClient(&cmc.Config{ ProAPIKey: "YOUR_API_KEY_HERE", }) // We're ready to rock! fmt.Println("CoinMarketCap client initialized!") }
Now for the fun part – let's grab some crypto data!
func main() { // ... client initialization ... listings, err := client.Cryptocurrency.LatestListings(&cmc.ListingOptions{ Limit: 10, }) if err != nil { log.Fatal(err) } for _, listing := range listings { fmt.Printf("%s: $%.2f\n", listing.Name, listing.Quote["USD"].Price) } }
The go-coinmarketcap package does a lot of the heavy lifting for us, but it's always good to add some error handling:
if err != nil { switch e := err.(type) { case *cmc.Error: fmt.Printf("CMC error: %s\n", e.Message) default: fmt.Printf("Error: %s\n", err) } return }
Let's create a function to display the top N cryptocurrencies:
func displayTopN(client *cmc.Client, n int) { listings, err := client.Cryptocurrency.LatestListings(&cmc.ListingOptions{ Limit: n, }) if err != nil { log.Fatal(err) } fmt.Printf("Top %d Cryptocurrencies:\n", n) for i, listing := range listings { fmt.Printf("%d. %s (%.2f%%)\n", i+1, listing.Name, listing.Quote["USD"].PercentChange24H) } }
Remember to play nice with the API! Implement some basic caching to avoid hitting rate limits:
import "time" var cache = make(map[string]interface{}) var cacheTTL = 5 * time.Minute func getCachedData(key string, fetcher func() (interface{}, error)) (interface{}, error) { if data, ok := cache[key]; ok { return data, nil } data, err := fetcher() if err != nil { return nil, err } cache[key] = data time.AfterFunc(cacheTTL, func() { delete(cache, key) }) return data, nil }
Let's wrap it all up with a simple CLI:
import "flag" func main() { client := cmc.NewClient(&cmc.Config{ ProAPIKey: "YOUR_API_KEY_HERE", }) topN := flag.Int("top", 10, "Display top N cryptocurrencies") flag.Parse() displayTopN(client, *topN) }
Now you can run your tool like this:
go run main.go -top 5
And there you have it! You've just built a nifty CoinMarketCap API integration in Go. From here, sky's the limit – maybe add some fancy charts, or create a web interface? The crypto world is your oyster!
Remember, always keep an eye on those API limits, and happy coding!