Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 23 of 60 · Go

Building a CLI with Cobra

Duration: 20 minutes

Cobra CLI Framework

This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.

Cobra powers kubectl, git, and many other tools.

package main

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

var rootCmd = &cobra.Command{ Use: "app", Short: "Demo CLI" }

var helloCmd = &cobra.Command{
    Use:   "hello [name]",
    Short: "Print a greeting",
    Args:  cobra.ExactArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Printf("Hello, %s!\n", args[0])
    },
}

func init() { rootCmd.AddCommand(helloCmd) }

func main() { rootCmd.Execute() }

Run it:

$ go run main.go hello World
Hello, World!

Persistent flags

rootCmd.PersistentFlags().BoolP("verbose", "v", false, "Enable verbose output")

Info

Cobra automatically generates help (--help) and completion scripts.

Previous: Dependency Management with Go ModulesNext: Working with Databases – `database/sql` and Drivers