Build A CLI in Golang

Build A CLI in Golang

ยท

4 min read

In a quest to improve my skills and proficiency in Golang, I built a simple CLI tool

I got this idea from John Crickett's coding challenges newsletter and It turned out to be quite easy and challenging at the same time.

Here is how you can build one yourself, tweak it, and change it as you deem fit.

First, you need to make a directory for the project where you will keep all the code related to this project.

mkdir wordCounter

Next, you need to change the directory into the newly created directory and create a new module and a go mod file that helps with dependency management

go mod init <name of module>

Next, you need a main.go file. This is like the entry point of your Golang applications

 touch main.go

In your directory, you would have two files a go.mod and main.go. You are set to build your first CLI tool in Golang.

You need to import some packages from Golang. Namely the "fmt", "os" and "strings"

"fmt": This is a package from Golang that handles input and output from the standard i/o which is also known as the terminal.

"os": This helps your Golang program interact with your operating system.

"strings": This helps you to manipulate strings.

Your main.go file show now have the following imports at the top

package main

import (

"fmt"
"os"
"strings"
)

Remember we are building a word counter CLI application which means we need a function that takes in text data and counts the words.

It is a simple function to write because strings have methods we can easily use to manipulate text.

func countWord (s string) int {
    return len(strings.Fields(s))
}

Fields strips strings around whitespace and return a slice of substrings.

Your program should look like this now.

 package main

import (

"fmt"
"os"
"strings"
)

func countWord (s string) int {
    return len(strings.Fields(s))
}

The next thing is to get this file path from your standard input/output in our case the terminal.

Remember one of the imports we imported earlier "os". This package from Golang allows us to interact with our operating system.

You can easily get the command line arguments using the below code

if len(os.Args) < 2 {
        fmt.Println("๐Ÿ“ File path not added")
        os.Exit(1)
    }

Args hold the command-line arguments, starting with the program name. In this case, if the length of the items in the array is less than 2 means the file path is not included in your command line arguments.

Now we can store this path in a variable.

filepath := os.Args[1]

Your code should look like this now

package main

import (

"fmt"
"os"
"strings"
)

func countWord (s string) int {
    return len(strings.Fields(s))
}

if len(os.Args) < 2 {
        fmt.Println("๐Ÿ“ File path not added")
        os.Exit(1)
    }

filepath := os.Args[1]

You just offered your CLI program the path of the file but you have done nothing to it yet. The contents of the file need to be read and the data extracted. Once again os package from Golang comes to our rescue.

data, err := os.ReadFile( filepath)

Just in typical Golang style, it checks if there was an error while performing this operation if encountered we can exit the application.

if err != nil {
        panic(err)
    }

Now we have everything we need to finish this CLI application. We have a function that takes in data and counts the words, we have a way to take input from the command line and we can open this input and see what it contains. Let us wrap this up.

    count := countWord(string(data))

    fmt.Println(count)

Here we just returned the value of the countWord function to a variable called count.

package main

import (
    "fmt"
    "os"
    "strings"

)

//function to return the count of the words in a text file 

func countWord (s string) int {
    return len(strings.Fields(s))
}

func main() {
        //Args hold the command-line arguments, starting with the program name. This check if the command have an argument
    if len(os.Args) < 2 {
        fmt.Println("๐Ÿ“ File path not added")
        os.Exit(1)
    }

    //store file path in a variable. This comes from the command line arguments which is an array 

    filepath := os.Args[1]

    // now we can read data from the file path
    data, err := os.ReadFile( filepath) 

    if err != nil {
        panic(err)
    }


    count := countWord(string(data))

    fmt.Println(count)
}

Congratulations you just created a CLI application in Golang. Below is a link to the github repo for the complete source code. Feel free to tweak and make modifications

https://github.com/Shoetan/golang-wordcounter

ย