Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Getting started with CLI's using Golang.
Siddhesh Khandagale
Siddhesh Khandagale

Posted on • Edited on

     

Getting started with CLI's using Golang.

Introduction :

In this blog we are going to get started with CLI usingGolang andCobra CLI. We are just going to make a simple Quiz game CLI and get friendly with the Cobra-CLI library.

Why Cobra-CLI?

Cobra is both a library for creating powerful modern CLI applications and a program to generate applications and CLI applications in Go. Cobra powers most of the popular Go applications including CoreOS, Delve, Docker, Dropbox, Git Lfs, Hugo, Kubernetes, and many more. With integrated command help, autocomplete and documentation.

Prerequisites :

To continue with tutorial, firstly you need to have Golang and Cobra-CLI installed.

Installation :

  • Golang
  • For installing Cobra-CLI you can go toCobra or rungo install github.com/spf13/cobra-cli@latest in the terminal.

Initializing the Project

After completing the Installation part to get started make a folder for eg.go_quiz , run the given command

go mod init github.com/Siddheshk02/go_quiz
Enter fullscreen modeExit fullscreen mode

In place ofSiddheshk02 use the name in which your project directories are. Now the structure will look like this

Image description

Cobra-cli init
Enter fullscreen modeExit fullscreen mode

This command initializes the CLI and make amain.go file along withcmd folder containingroot.go

Image description

Themain.go file will have the following code,

package mainimport "github.com/Siddheshk02/go_quiz/cmd"func main() {    cmd.Execute()}
Enter fullscreen modeExit fullscreen mode

This means the main cli commands implementation will be incmd which is called throughmain.go.

Make the following changes in theroot.go file.

package cmdimport (    "os"    "github.com/spf13/cobra")var rootCmd = &cobra.Command{    Use:   "go_quiz",    Short: "A Simple Quiz game CLI",    Long: `A Simple Quiz game CLI using Golang.`,}func Execute() {    err := rootCmd.Execute()    if err != nil {        os.Exit(1)    }}func init() {    rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")}
Enter fullscreen modeExit fullscreen mode

Inroot.go, functionExecute gets called frommain.go and it executes therootCmd.Use is used to define the command to be used andShort andLong contains the information or description for the Command in short and long format respectively.

Now rungo run main.go orgo build . and.\go_quiz orgo_quiz.

C:\Users\Admin\Go\src\github.com\Siddheshk02\go_quiz> go run main.goA Simple Quiz game CLI using Golang.
Enter fullscreen modeExit fullscreen mode
C:\Users\Admin\Go\src\github.com\Siddheshk02\go_quiz> go build .C:\Users\Admin\Go\src\github.com\Siddheshk02\go_quiz> .\go_quizA Simple Quiz game CLI using Golang.
Enter fullscreen modeExit fullscreen mode
C:\Users\Admin\Go\src\github.com\Siddheshk02\go_quiz>go_quiz -h       A Simple Quiz game CLI using Golang.Usage:  go_quiz [flags]  go_quiz [command]Available Commands:  completion  Generate the autocompletion script for the specified shell  help        Help about any command  start       Starting a new QuizFlags:  -h, --help     help for go_quiz  -t, --toggle   Help message for toggleUse "go_quiz [command] --help" for more information about a command.
Enter fullscreen modeExit fullscreen mode

Now let's make a csv filedata.csv in thego_quiz directory, to store the questions and answers for the quiz.

Store the following values in the file.

5+5,107+3,101-1,08+3,111+2,38-6,23-1,21+4,55-1,42+3,53+3,67-4,35+2,79-2,74+8,121+8,9
Enter fullscreen modeExit fullscreen mode

Lets make a new command which will be used to start a Quiz.

for adding a new command run this codeCobra-cli add start, herestart is the new command made.

This will create a new filestart.go in the cmd folder.

Image description

Make the following changes in thestart.go file

package cmdimport (    "fmt"    "github.com/spf13/cobra")var startCmd = &cobra.Command{    Use:   "start",    Short: "Starting a new Quiz",    Run: func(cmd *cobra.Command, args []string) {        fmt.Println("start called")    },}func init() {    rootCmd.AddCommand(startCmd)}
Enter fullscreen modeExit fullscreen mode

let's try running our new command. Rungo build . in the terminal and then rungo_quiz start

C:\Users\Admin\Go\src\github.com\Siddheshk02\go_quiz>go_quiz start    start called
Enter fullscreen modeExit fullscreen mode

you can also try runninggo_quiz start -h.

Now, for the main implementation of the Quiz game, we will make a folder pkg in the project directory i.e.go_quiz and a filequiz.go in the pkg folder.

Image description
In thequiz.go make a functionQuiz that returns a stringres

func Quiz() (res string) {    return res}
Enter fullscreen modeExit fullscreen mode

This function will be called in thestart.go as :

Run: func(cmd *cobra.Command, args []string) {        res := pkg.Quiz},
Enter fullscreen modeExit fullscreen mode

Now, let's code in theQuiz function inquiz.go

Firstly, we need to open and read thedata.csv file to get the questions and there answers.

package pkgimport (    "encoding/csv"    "errors"    "fmt"    "io"    "log"    "os"    "strconv")func Quiz() (res int, err error) {    res = 0    f, err := os.Open("C:/Users/Admin/Go/src/github.com/Siddheshk02/go_quiz/data.csv")    if err != nil {        log.Fatal(err)    }    defer f.Close()    csvReader := csv.NewReader(f)    var ans int    for {        rec, err := csvReader.Read()        if err == io.EOF {            break        }        if err != nil {            log.Fatal(err)        }        fmt.Print(rec[0] + " : ")        c, _ := strconv.Atoi(rec[1])        fmt.Scanf("%d\n", &ans)        if ans == c {            res = res + 1            fmt.Println("correct")            continue        } else {            err = errors.New("Incorrect Response!!")            break        }    }    return res, err}
Enter fullscreen modeExit fullscreen mode

Here, we are taking the questions and answers inrec which is a string array, so for each iteration in the loop therec array takes question inrec[0] and answer inrec[1].

Then for comparing the user inputans with the original answer i.e.rec[1], we first convertrec[1] into integer type asans is in integer whereasrec is string.

Ares variable is created to store the result count, which is returned along witherr error after completing the quiz or after giving an Incorrect response.

So, thestart.go will look like the following code after all changes :

Run: func(cmd *cobra.Command, args []string) {        res, err := pkg.Quiz()        if err != nil {            fmt.Println(err)            fmt.Printf("Your Score is %d", res)        } else {            if res == 16 {                fmt.Println("Congrats!, you got all questions Correct")            }            fmt.Printf("Your Score is %d", res)        }    },
Enter fullscreen modeExit fullscreen mode

Now, rungo build . and thengo_quiz start to test the CLI.

C:\Users\Admin\Go\src\github.com\Siddheshk02\go_quiz>go_quiz start 5+5 :
Enter fullscreen modeExit fullscreen mode

Enter the answers after getting the question :)

If all the given responses are correct

...1+8 : 9correctCongrats!, you got all questions CorrectYour Score is 16
Enter fullscreen modeExit fullscreen mode

And if any of the response is Incorrect :(

..7+3 : 10correct1-1 : 0correct8+3 : 1 Your Score is 3
Enter fullscreen modeExit fullscreen mode

The complete code is saved onGitHub

Conclusion :

In this tutorial we learnt how to create a command-line application with Go and Cobra. In the next upcoming tutorial , we will learn how to add flags, commands, etc. and build more such amazing stuff.

If you enjoyed this article and you'd like more, consider followingSiddhesh on Twitter to get the latest updates.

Congratulations🎉, you did great. Keep learning and keep coding :)

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Backend Developer specialized in Web Apps, CLI tools, and AI integration with Golang.
  • Pronouns
    He/Him
  • Work
    Freelance Developer
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp