Write a CLI tool with T.D.D (Weather CLI)

Through these instructions, you will learn how to initiate a CLI tool using Golang. The CLI tool we are going to create step by step is a Weather CLI that helps us to get different attributes of the current weather including the current weather description, temperature and humidity.

In this tutorial example, our CLI tool is dependent on a weather API service from https://openweathermap.org/api which is accessible through internet.

Here is the step by step help:

  1. Like other Golang projects, you need to create your project under $GOPATH/src. I’m creating my gotutorial projects like this:
    $ mkdir -p $GOPATH/src/github.com/gotutorial/weather-cli
    $ cd $GOPATH/src/github.com/gotutorial/weather-cli
  2. Create the weather-cli main go file which is the starting point of your application. I called it weather.go, you can name it whatever you like.
    $ vi weather.go
  3. Your main file should have at least a line defining the package that main function is in it. main function is the starting point of your Go application.
    Add following content to weather.go file:

    package main
    
    func main() {
    }
  4. I used https://github.com/urfave/cli golang library to implement this CLI project. 
    Add following import and instantiate the CLI application like this:

    package main 
    
    import (
    	"github.com/urfave/cli"
    )
    
    func main() {
         app := cli.NewApp()
    }
  5. You can set a value to app.Name attribute which identifies your CLI application name. app.Usage is the usage description of your CLI app and app.Version specifies your CLI app version. Add app.Run(os.Args) to run your CLI application
    package main 
    
    import (
    	"github.com/urfave/cli"
    )
    
    func main() {
         app := cli.NewApp() // Instantiate a new CLI application
         app.Name = "Weather CLI Tool" // Assign the name of the CLI app
         app.Usage = "Prompt the current weather condition for a city" // Assign the usage description for the CLI 
         app.Version = "1.0.0" //Assign the version of the CLI app
    
         app.Run(os.Args)
    }
     
  6. Build you application using following command:
    $ go build -o weather
  7. An executable file will be generated as the result. Run it like this and you see the help and usage information as follow:
    $ ./weather
    NAME:
       Weather CLI Tool - Prompt the current weather condition for a city
    
    USAGE:
       weather [global options] command [command options] [arguments...]
    
    VERSION:
       1.0.0
    
    COMMANDS:
         help, h  Shows a list of commands or help for one command
    
    GLOBAL OPTIONS:
       --help, -h     show help
       --version, -v  print the version

     

 

Leave a Reply