DevPrep
  • Interview Prep
  • Projects
  • Resources
  • Pricing
  • About Us
Submit Question
DevPrep
  • Pricing
  • About Us
Submit Question

Practice

  • JavaScript
  • DSA
  • Machine Coding
  • System Design

Resources

  • Learning Tracks
  • Articles
  • Roadmaps
  • Compare Concepts
  • Glossary
  • Developer Tools
  • All Questions

Company

  • About
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service
DevPrep

© 2026 DevPrep. All rights reserved.

← Back to Questions
EasyTheory

Cobra: Building CLI Applications in Go

339 views

Problem Statement

Build a professional CLI application using Cobra, the framework behind kubectl, docker, and hugo.

Project Structure

mycli/
├── cmd/
│   ├── root.go
│   ├── serve.go
│   └── migrate.go
├── main.go
└── go.mod

main.go

package main

import "mycli/cmd"

func main() {
    cmd.Execute()
}

cmd/root.go

package cmd

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

var (
    cfgFile string
    verbose bool
)

var rootCmd = &cobra.Command{
    Use:   "mycli",
    Short: "My awesome CLI application",
    Long: `A longer description that spans multiple lines.`,
}

func Execute() {
    if err := rootCmd.Execute(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

func init() {
    cobra.OnInitialize(initConfig)
    
    // Persistent flags (available to all subcommands)
    rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", 
        "config file (default $HOME/.mycli.yaml)")
    rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, 
        "verbose output")
    
    viper.BindPFlag("verbose", rootCmd.PersistentFlags().Lookup("verbose"))
}

func initConfig() {
    if cfgFile != "" {
        viper.SetConfigFile(cfgFile)
    } else {
        home, _ := os.UserHomeDir()
        viper.AddConfigPath(home)
        viper.SetConfigName(".mycli")
    }
    viper.AutomaticEnv()
    viper.ReadInConfig()
}

cmd/serve.go

package cmd

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

var (
    port int
    host string
)

var serveCmd = &cobra.Command{
    Use:   "serve",
    Short: "Start the server",
    Long:  "Start the HTTP server with specified configuration",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Printf("Starting server on %s:%d\n", host, port)
        // Start server...
    },
}

func init() {
    rootCmd.AddCommand(serveCmd)
    
    serveCmd.Flags().IntVarP(&port, "port", "p", 8080, "Port to listen on")
    serveCmd.Flags().StringVar(&host, "host", "0.0.0.0", "Host to bind to")
    
    // Mark flag as required
    serveCmd.MarkFlagRequired("port")
}

Subcommand with Arguments

var mathCmd = &cobra.Command{
    Use:   "math",
    Short: "Mathematical operations",
}

var addCmd = &cobra.Command{
    Use:   "add [numbers...]",
    Short: "Add numbers together",
    Args:  cobra.MinimumNArgs(2),
    Run: func(cmd *cobra.Command, args []string) {
        sum := 0
        for _, arg := range args {
            n, _ := strconv.Atoi(arg)
            sum += n
        }
        fmt.Printf("Sum: %d\n", sum)
    },
}

func init() {
    rootCmd.AddCommand(mathCmd)
    mathCmd.AddCommand(addCmd)
}

// Usage: mycli math add 1 2 3 4
// Output: Sum: 10

Generate Documentation

import "github.com/spf13/cobra/doc"

// Generate Markdown docs
doc.GenMarkdownTree(rootCmd, "./docs")

// Generate man pages
doc.GenManTree(rootCmd, nil, "./man")

Sample Test Cases

Case 1
Input
cmd: myapp greet --name=John
Expected Output
Output: Hello, John!
Case 2
Input
cmd: myapp --help
Expected Output
Shows usage and available commands

No solutions yet

Be the first to share a solution for this question.

Comments (0)

Sign in to leave a comment.

No comments yet. Be the first to comment.

Stats

Views
339
Likes
0
Solutions
0
Comments
0

Category

Backend Engineering

Languages

Go