KERNEL PANIC

FATAL_ERROR: RED_BULL_RESERVOIR_EMPTY

A problem has been detected and systems have been shut down to prevent damage to your sanity.


*** STOP: 0x000000GO (0x000000RU, 0x000000ST, 0x000000SRE, 0x000000AI)


Rebooting in 5 seconds...

Originally published on an external platform.

Go has a rich ecosystem of libraries maintained by the community. One of the standout libraries for building command-line applications is Cobra. It powers some of the most popular CLI tools in the industry. Today, weโ€™ll explore how to use this library to build a functional CLI application.

Go CLI

Goal: Build a simple CLI app named url-monitor using Cobra that implements sub-commands and handles arguments.

The Requirements

We want to build an app with two primary sub-commands:

  1. check-url: Validates if a URL is reachable.
  2. check-status: Retrieves the status payload from an API endpoint.

Both commands will take a URL/API endpoint as an mandatory argument.

Project Structure

This is how our Go project, url-monitor, will be organized:

url-monitor/
โ”œโ”€โ”€ commands/
โ”‚   โ”œโ”€โ”€ check-status.go
โ”‚   โ”œโ”€โ”€ check-url.go
โ”‚   โ”œโ”€โ”€ helpers.go
โ”‚   โ””โ”€โ”€ root.go
โ”œโ”€โ”€ go.mod
โ””โ”€โ”€ main.go

Implementation

1. main.go

This is the entry point of our application. It simply calls the Execute function from our commands package.

package main

import "url-monitor/commands"

func main() {
   commands.Execute()
}

2. root.go

The root.go file defines the base command and handles initialization. We use the init() function to set up our sub-commands.

package commands

import (
   "log"
   "github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
   Use:   "url-monitor",
   Short: "A simple API monitoring CLI",
   Long:  `url-monitor is a lightweight tool built with Go and Cobra to monitor API health and status.`,
}

func init() {
   // Adding sub-commands to the root command
   rootCmd.AddCommand(checkUrlCmd, checkStatusCmd)
}

func Execute() {
   if err := rootCmd.Execute(); err != nil {
      log.Fatal(err)
   }
}

3. check-url.go

This sub-command validates the URL format and checks for a 200 OK status.

package commands

import (
   "fmt"
   "net/url"
   log "github.com/sirupsen/logrus"
   "github.com/spf13/cobra"
)

var checkUrlCmd = &cobra.Command{
   Use:   "check-url [url]",
   Short: "Verify a URL is valid and reachable",
   Args:  cobra.ExactArgs(1),
   Run: func(cmd *cobra.Command, args []string) {
      targetURL := args[0]
      if _, err := url.ParseRequestURI(targetURL); err != nil {
         log.Fatalf("Invalid URL provided: %s", err)
      }
      
      fmt.Printf("Checking URL: %s...\n", targetURL)
      // Implementation logic here...
   },
}

Building and Running

First, initialize the modules and fetch dependencies:

>> go mod init url-monitor
>> go mod tidy

Build the binary:

>> go build -o url-monitor .

Testing the CLI

Running the base command:

>> ./url-monitor
A simple API monitoring CLI

Usage:
  url-monitor [command]

Available Commands:
  check-status Verify API payload status
  check-url    Verify a URL is valid and reachable
  completion   Generate the autocompletion script for the specified shell
  help         Help about any command

Flags:
  -h, --help   help for url-monitor

Executing a sub-command:

>> ./url-monitor check-url https://google.com
Checking URL: https://google.com...

Handling an error:

>> ./url-monitor check-url invalid-uri
FATAL Invalid URL provided: parse "invalid-uri": illegal character in scheme

Why use Cobra?

Cobra is the industry standard for Go-based CLIs. It is used by massive projects like Kubernetes, Hugo, GitHub CLI, and Docker. It handles nested sub-commands, global/local flags, and help generation out of the box.

If you are looking for alternatives, check out mitchellh/cli or urfave/cli.

Happy Coding!!

36.5ยฐC
CORE TEMPERATURE

KERNEL PANIC

Critical system failure. All Gophers have escaped.

Rebooting universe in 5...

Error: PEBKAC_EXCEPTION
Address: 0xDEADBEEF