Building a CLI for Cryptocurrency Price Tracking in Go

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating the CLI
  5. Displaying Cryptocurrency Prices
  6. User Input and Menu Navigation
  7. Adding Extra Features
  8. Conclusion

Introduction

In this tutorial, we will build a command-line interface (CLI) application in Go for tracking cryptocurrency prices. By the end of this tutorial, you will be able to fetch and display cryptocurrency prices, navigate through a menu, and add extra features to enhance the functionality of your CLI application.

Prerequisites

To follow this tutorial, you should have a basic understanding of Go programming language syntax and concepts. It is also recommended to have Go installed on your machine.

Setup

To set up your development environment, follow these steps:

  1. Install Golang by downloading the binary distribution suitable for your operating system from the official Go website.

  2. Configure the environment variables. For example, add the following line to your .bash_profile or .zshrc file:
     export PATH=$PATH:/usr/local/go/bin
    
  3. Verify the installation by opening a new terminal window and running the following command:
     go version
    

    You should see the installed Go version printed in the terminal.

Creating the CLI

  1. Create a new directory for your project and navigate into it:
     mkdir crypto-tracker && cd crypto-tracker
    
  2. Create a new Go module:
     go mod init github.com/your-username/crypto-tracker
    
  3. Create a new file named main.go and open it in your favorite text editor.

  4. Import the necessary packages:
     package main
        
     import (
         "fmt"
         "os"
     )
    
  5. Define a main function:
     func main() {
         fmt.Println("Welcome to Crypto Tracker CLI!")
     }
    
  6. Build and run the application:
     go build && ./crypto-tracker
    

    You should see the message “Welcome to Crypto Tracker CLI!” printed in the terminal.

Displaying Cryptocurrency Prices

  1. Install the necessary packages for making HTTP requests:
     go get github.com/go-resty/resty/v2
    
  2. Import the new package into your main.go file:
     import (
         "fmt"
         "os"
        
         "github.com/go-resty/resty/v2"
     )
    
  3. Create a function named getCryptoPrices that retrieves cryptocurrency prices by making an HTTP GET request to a public API:
     func getCryptoPrices() {
         client := resty.New()
         response, err := client.R().Get("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,litecoin&vs_currencies=usd")
         if err != nil {
             fmt.Println("Failed to retrieve cryptocurrency prices.")
             os.Exit(1)
         }
         fmt.Println(string(response.Body()))
     }
    
  4. Modify the main function to call getCryptoPrices:
     func main() {
         fmt.Println("Welcome to Crypto Tracker CLI!")
         getCryptoPrices()
     }
    
  5. Build and run the application:
     go build && ./crypto-tracker
    

    You should now see a JSON response containing the prices of Bitcoin, Ethereum, and Litecoin.

User Input and Menu Navigation

  1. Modify the main function to display a menu for the user to select options:
     func main() {
         fmt.Println("Welcome to Crypto Tracker CLI!")
        
         var choice int
         for choice != 3 {
             fmt.Println("\nMenu:")
             fmt.Println("1. View Cryptocurrency Prices")
             fmt.Println("2. Exit")
             fmt.Print("Enter your choice: ")
             _, err := fmt.Scanln(&choice)
             if err != nil {
                 fmt.Println("Invalid choice. Please try again.")
             }
        
             switch choice {
             case 1:
                 getCryptoPrices()
             case 2:
                 fmt.Println("Exiting Crypto Tracker CLI...")
                 os.Exit(0)
             default:
                 fmt.Println("Invalid choice. Please try again.")
             }
         }
     }
    
  2. Build and run the application:
     go build && ./crypto-tracker
    

    You can now navigate the menu by entering the corresponding option number.

Adding Extra Features

  1. Modify the getCryptoPrices function to parse and display the actual cryptocurrency prices from the API response:
     import (
         "encoding/json"
         // ...
        
     func getCryptoPrices() {
         // ...
        
         var prices map[string]map[string]float64
         if err := json.Unmarshal(response.Body(), &prices); err != nil {
             fmt.Println("Failed to parse cryptocurrency prices.")
             os.Exit(1)
         }
        
         fmt.Println("\nCryptocurrency Prices:")
         for name, data := range prices {
             fmt.Printf("%s: %.2f USD\n", name, data["usd"])
         }
     }
    
  2. Build and run the application:
     go build && ./crypto-tracker
    

    You should now see the actual prices of Bitcoin, Ethereum, and Litecoin instead of the raw JSON response.

Conclusion

In this tutorial, you learned how to build a CLI for cryptocurrency price tracking in Go. You started by setting up your development environment, followed by creating the CLI application structure. Then, you added functionality to fetch and display cryptocurrency prices from a public API. Additionally, you implemented menu navigation and provided an option to exit the application. Finally, you enhanced the application by parsing the API response and displaying the actual cryptocurrency prices.

You are now equipped with the knowledge to expand this application further and add more features, such as historical price tracking or portfolio management.