
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 run
go 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
In place ofSiddheshk02
use the name in which your project directories are. Now the structure will look like this
Cobra-cli init
This command initializes the CLI and make amain.go
file along withcmd
folder containingroot.go
Themain.go
file will have the following code,
package mainimport "github.com/Siddheshk02/go_quiz/cmd"func main() { cmd.Execute()}
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")}
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.
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.
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.
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
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.
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)}
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
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.
In thequiz.go
make a functionQuiz
that returns a stringres
func Quiz() (res string) { return res}
This function will be called in thestart.go
as :
Run: func(cmd *cobra.Command, args []string) { res := pkg.Quiz},
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}
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) } },
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 the answers after getting the question :)
If all the given responses are correct
...1+8 : 9correctCongrats!, you got all questions CorrectYour Score is 16
And if any of the response is Incorrect :(
..7+3 : 10correct1-1 : 0correct8+3 : 1 Your Score is 3
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)
For further actions, you may consider blocking this person and/orreporting abuse