---
title: Golang Tutorial - How to Implement CLI App in 4 Steps Using Cobra?
description: Looking for some Golang tutorial, to get a deepen knowledge of go language? We prepared for you something exactly like that! CLI implementation using cobra
image: https://blog-hubspot.railwaymen.org/hubfs/golang%20tutorial%20for%20beginners%20(1).jpg
---

[![Railwaymen](https://blog-hubspot.railwaymen.org/hs-fs/hubfs/Railwaymen_September2018/Images/logo_bia%C5%82e.png?width=260&height=70&name=logo_bia%C5%82e.png "Railwaymen")](https://railwaymen.org/)

- [Blog Main Page](https://blog-hubspot.railwaymen.org)
- [About Us](https://railwaymen.org/about-us)
- [Our Work](https://railwaymen.org/case-studies)
- [FAQ](https://railwaymen.org/our-ai-knowledge-base)
- [Contact Us](https://railwaymen.org/contact-us)

![golang tutorial - how to implement cli app in 4 steps using cobra?](https://blog-hubspot.railwaymen.org/hs-fs/hubfs/golang%20tutorial%20for%20beginners%20(1).jpg?width=1320&name=golang%20tutorial%20for%20beginners%20(1).jpg)

[Web Development](https://blog-hubspot.railwaymen.org/tag/web-development)

# Golang Tutorial - How to Implement CLI App in 4 Steps Using Cobra?

- [Michał Szymański, Senior RoR Developer](https://blog-hubspot.railwaymen.org/author/michał-szymanski-senior-ror-developer)
- [25th February '20](https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library)

According to the research, there are between 500 and 2000 active general-purpose programming languages around the world. That's a crazy lot! Yet - the new languages still appear, dethroning some of the old ones. That's why as a self-aware developer you should keep an eye on the latest trends on the market because who knows, maybe the language that you are developing your apps in today, won't be as desirable in the future?

And even if it's not the case - programmers today are required to know more than just one programming language. It's also good for your mental health (avoiding getting burned out) to know some other technologies, that you can experiment in. So if you are looking for some new programming language, to expand your horizons - we have some proposition for you!

### Table of Contents:

[1.  Golang introduction - basic features & language advantages](https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library#pa)

[2. What is Golang good for & companies that use it](https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library#pb)

[3. Golang tutorial - the app purpose & library introduction](https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library#pc)

[4. Go programming tutorial - let's start coding!](https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library#pd)

[5. Summary and conclusion](https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library#pe)

## Golang introduction - basic features & language advantages

Go is an open-source programming language (also known as Golang) and it has been developed by Google in 2009. The language Go speed, simplicity, and reliability make it the perfect choice for all kinds of developers. It is used to implement any kind of app: [web app](https://railwaymen.org/services/web-development)**,

CLI, machine learning tools.**

The main reasons why I have decided to use the Go language are:

**- fast performance**

Golang is compiled to machine code and its compilation is very fast. The language links all dependency into a binary file.

**- easy concurrency model**

This makes it easy to progress with multiple tasks at the same time. Concurrency is an integral part of Go, supported by goroutines, channels.

**- easiness to learn**

Compare to other programming languages like C, C++, Rust etc., Go is easy to learn.

**- cross-platform**

You can write code in any environment you like - OS-X, Linux, FreeBSD, or Windows.

## What is Golang good for & companies that use it

Some of the biggest companies worldwide have already discovered the potential of Go, using it for their business purposes. You can find some examples of them below:

- Google
- digitalocean.com
- Airbrake
- Atlassian
- and more other

Golang is great to build the Command Line Interface (CLI) app. In this tutorial, I'm going to present step by step how to implement that CLI app using Go lang and Cobra package. Because I believe it is the best way to learn Golang - based on a real-life challenge. At the [Railwaymen Software House](https://railwaymen.org/about-us) where I work at, we constantly looking for the best tech stack to fulfill our [partners technological and business needs](https://railwaymen.org/case-studies). And I already see, that Go lang is an excellent language to do it!

There are many CLI apps implemented using Golang ie. Docker, Kubernetes, [Hugo](https://gohugo.io/). The biggest advantage of this kind of apps are:

- the app is lightweight
- it's easy to run using terminal scripts i.e zsh, bash
- the app is fast
- there are no dependencies
- it is best for task-based automation

[Read more about Golang Benefits here!](https://blog-hubspot.railwaymen.org/why-use-golang-to-build-your-business-app)

## Golang tutorial - the app purpose & library introduction

### The Golang "duplicate" app

The app in the tutorial will provide the main features:

- 1) create dir for files
- 2) copy files to the destination directory

I assume that You have already installed a Golang and set up a development environment for it. The library which is the best match in the case of the CLI app is [Cobra](https://github.com/spf13/cobra).

### Golang tutorial - Cobra library introduction

Before we start using the Cobra library we need to get to know the concepts behind it.

*"Cobra is built on a structure of commands, arguments & flags. Commands represent actions, Args are things and Flags are modifiers for those actions."* - [Cobra github](https://github.com/spf13/cobra#concepts)

The structure will be like

```

APPNAME Command Args --flags
```

Example app execute in console

- docker ps -a
- Hugo new site example.com

## Go programming tutorial - let's start coding!

If you want to learn golang, this tutorial will show you how you can tackle a specific challenge considering CLI apps, that as developers we often encounter. Enjoy and feel free to let me know in the comment section if anything requires further elaboration!

### Step 1: Creating the project in Golang

Cobra library provides initializator command for the new project. Let's init base CLI structure using cobra.

```

cobra init --pkg-name github.com/michalsz/duplicator
duplicator
```

 

Inside the project dir.

```

cd duplicator
```

 

Add new action duplicate

```

cobra add duplicate
```

 

Structure of the project

```

duplicate/
  cmd/
    root.go
    duplicate.go
  main.go
```

 

The main.go is the entry point of the CLI. Inside the main.go it is calling the Execute function of the

```

cmd/root.go
.
package main

import "github.com/michalsz/duplicator/cmd"

func main() {
        cmd.Execute()
}
```

Let's look to root.go The main part of root.go is our command rootCmd where we define it.

```

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "duplicator",
	Short: "A brief description of your application",
	Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	//	Run: func(cmd *cobra.Command, args []string) { },
}

```

Build the app without defining any code for root command

```

go build -o  duplicator main.go && ./duplicator duplicate
```

As a result we get only print in terminal

```

duplicate called
```

### Step 2: Let's define a flag for our duplicate command

Define var 'fileExt' to store file extension which kind of file we are going to copy.

```

var fileExt string

	// duplicateCmd represents the duplicate command
	var duplicateCmd = &cobra.Command{

```

Add definition flag to *init()* function in duplicate.go file. Look that the flag extension is required.

```

	duplicateCmd.Flags().StringVarP(&fileExt, "extension", "e", "", "file extension is required")
	duplicateCmd.MarkFlagRequired("extension")
```

And print fileExt var in Run section of our command

```

Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("duplicate called")
		fmt.Println(fileExt)
	},

```

Let's build and run it.

```

go build -o  duplicator main.go && ./duplicator duplicate -f txt
```

As result we get print in console

```

 duplicate called
  txt
```

 

### Step 3: Let's define a new flag 'dirName' which store handle dir name where the file will be duplicated.

 

```

	var dirName string

func init() {
	fmt.Println("init called")
	duplicateCmd.Flags().StringVarP(&fileExt, "extension", "e", "", "file extension is required")
	duplicateCmd.MarkFlagRequired("extension")
	duplicateCmd.PersistentFlags().StringVarP(&dirName, "dirname", "d", "copied_files", "dir to copie")
	rootCmd.AddCommand(duplicateCmd)

}

```

 

We see that the flag -d is not required and has default value copied\_files for the dir.

 

### Step 4: Let's add a new command which prints the version of our app

 

```

	cobra add version
```

 

Add *version* function to version.go file.

```

func version(){
	fmt.Println("v0.1")
}
```

And call it in Run section.

Run: func(cmd \*cobra.Command, args \[\]string) { fmt.Println("version called") version() },

## Summary and conclusion

I have decided to use the Cobra package since it is really easy to integrate it with the base code of any application. The best in Cobra package is that it organizes commands into dedicated command file ie. *duplicate.go* The package also auto-generate man pages for your command. I see big potential in this package.

**Do you want to deepen your Golang knowledge even more? I've recently published a video tutorial about how to implement Clean Architecture Principles in Go.**

[You can check it here!](https://blog-hubspot.railwaymen.org/golang-clean-architecture-in-projects)

[Web Development](https://blog-hubspot.railwaymen.org/tag/web-development)

- Share:
- <https://twitter.com/share?text=Golang%20Tutorial%20-%20How%20to%20Implement%20CLI%20App%20in%204%20Steps%20Using%20Cobra?&url=https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library>
- <http://www.facebook.com/sharer/sharer.php?u=https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library>
- <http://www.reddit.com/submit?url=https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library&title=Golang%20Tutorial%20-%20How%20to%20Implement%20CLI%20App%20in%204%20Steps%20Using%20Cobra>
- <https://www.pinterest.com/pin/create/button/?url=https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library>
- <http://www.linkedin.com/shareArticle?mini=true&url=https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library>

![Michał Szymański, Senior RoR Developer](https://blog-hubspot.railwaymen.org/hubfs/Group%201-8%20(1).png)

Author

#### [Michał Szymański, Senior RoR Developer](https://blog-hubspot.railwaymen.org/author/michał-szymanski-senior-ror-developer)

- <https://www.linkedin.com/in/michal-szymanski-01a6a25/>

 Michał is an experienced RoR and Go software developer. After work, he is an active person, who loves running or cycling around the Kraków.

##### [![how gpt-5 will change your business and give you a competitive edge?](https://blog-hubspot.railwaymen.org/hs-fs/hubfs/GPT-5%20(1).jpg?width=305&name=GPT-5%20(1).jpg) Related Article Business and Technology How GPT-5 will change your business and give you a competitive edge? 5 min read Full Article](https://blog-hubspot.railwaymen.org/gpt-5-revolution-business-advantage)

##### [![how to build a scalable microservice architecture?](https://blog-hubspot.railwaymen.org/hs-fs/hubfs/pexels-jean-daniel-4006158.jpg?width=305&name=pexels-jean-daniel-4006158.jpg) Related Article Business and Technology How to build a scalable microservice architecture? 19 min read Full Article](https://blog-hubspot.railwaymen.org/scalable-microservice-architecture)

##### [![how rag makes generative ai truly reliable for your business?](https://blog-hubspot.railwaymen.org/hs-fs/hubfs/what%20is%20rag%20in%20ai.jpg?width=305&name=what%20is%20rag%20in%20ai.jpg) Related Article Business and Technology How RAG Makes Generative AI Truly Reliable for Your Business? 7 min read Full Article](https://blog-hubspot.railwaymen.org/how-rag-makes-gen-ai-reliable-for-business)

## [![how to become a better junior developer: 5 habits to learn right away](https://blog-hubspot.railwaymen.org/hs-fs/hubfs/junior%20web%20developer%20tasks.jpg?width=1905&height=510&name=junior%20web%20developer%20tasks.jpg) Next Post --- How to Become a Better Junior Developer: 5 Habits to Learn Right Away Web Development](https://blog-hubspot.railwaymen.org/how-to-become-a-good-junior-web-developer-5-healthy-habits-to-learn-right-away)

[![Railwaymen Logo](https://railwaymen.org/assets/svgs/rwm-logo-white-ae5182ba602bcbf3713fd6bb3a5288956e484b62ddf1c647e53f2fb72644913d.svg)](https://railwaymen.org)

 Railwaymen Sp. z o.o.   
 Email: info@railwaymen.org   
 NIP: 6793065841

[![European Funds Smart Growth](https://railwaymen.org/assets/icons/logos/unia-98bb8c7ed12fa79f2ddbe0e00b222213700102dba79748d59f43a304d9803de6.png)](https://railwaymen.org/grants)

[Estimate Project](https://railwaymen.org/estimate-project) [Newsletter Subscribe](https://learn.railwaymen.org/newsletter)

- <https://www.linkedin.com/company/railwaymen>
- <https://www.facebook.com/railwaymen.software.development>
- <https://www.youtube.com/channel/UCu5v1NuohjsTZXGV4K60KWA>
- <https://www.instagram.com/railwaymen_org>
- <https://twitter.com/Railwaymen_org>
- <https://dribbble.com/Railwaymen_org>
- <https://www.behance.net/railwaymen>

##### Company

- [Services](https://railwaymen.org/services)
- [Our Work](https://railwaymen.org/case-studies)
- [About us](https://railwaymen.org/about-us)
- [Blog](https://blog.railwaymen.org)
- [Career](https://railwaymen.org/careers)
- [Personal Data Protection](https://railwaymen.org/personal-data-protection)
- [Cookies Policy](https://railwaymen.org/docs/Cookie_Policy.pdf)
- Cookie Settings

##### Services

- [Web Development](https://railwaymen.org/services/web-development)
- [Mobile Development](https://railwaymen.org/services/mobile-development)
- [Product Design](https://railwaymen.org/services/product-design)
- [Discovery Phase](https://railwaymen.org/services/discovery-phase)
- [MVP Development](https://railwaymen.org/services/mvp-development)
- [Digital Transformation](https://railwaymen.org/services/digital-transformation)
- [Social Networking Software](https://railwaymen.org/services/social-networking-software)
- [Restaurant App Development](https://railwaymen.org/services/restaurant-app-development)
- [Construction Sofware Development](https://railwaymen.org/services/construction-software-development)
- [Custom Marketing Software Development](https://railwaymen.org/services/custom-marketing-software-development)
- [FinTech App Development](https://railwaymen.org/services/fintech-development)

##### Our Experts Must - Reads

- [Is Ruby on Rails Dead in 2025?](https://blog.railwaymen.org/is-ruby-on-rails-dead)
- [How to Start an App Development Project? \[Checklist\]](https://blog.railwaymen.org/checklist-what-you-have-to-do-to-start-the-app-development-project)
- [How to Build an MVP? \[5 Steps\]](https://blog.railwaymen.org/how-to-build-an-mvp)
- [How Long Does it Take to Make An App in 2025?](https://blog.railwaymen.org/how-long-does-it-take-to-make-an-app)
- [Agile Discovery Phase: a Must Have for Your Business](https://blog.railwaymen.org/why-a-discovery-phase-is-a-must-have-for-your-project)
- [Railwaymen App Development Cost Breakdown - How Much do We Charge and Why?](https://blog.railwaymen.org/app-development-cost-breakdown)
- [FAQ: Web & Mobile Development With Us Explained](https://blog.railwaymen.org/railwaymen-faq-web-and-mobile-development-with-us-explained)

 Awards

[![Clutch Recognition Best B2B Companies Global](https://railwaymen.org/assets/awards/Top_B2B_Companies_Global_2018-5d1c8e5358737540e214ce8d51e450fe06ac4be35a0a220c0c2ccfa912787879.png)](https://clutch.co/profile/railwaymen)[![Clutch Recognition Best Ruby on Rails Developers](https://railwaymen.org/assets/awards/ClutchAward2021-013bdba335eecb6eb59319b0475d099899bbb2fa50e4596186ea2126d5b606af.png)](https://clutch.co/press-releases/recognizes-top-performing-development-companies-poland-2021)[![Clutch Top Ruby on Rails Developer Poland 2022](https://railwaymen.org/assets/awards/ClutchTopSoftwareDeveloperPoland_2022-d094b46bd3ce96c9355d21d0c6a05bc4f5959ec255f6815af8797c0a938a6b9e.png)](https://clutch.co/profile/railwaymen)[![Clutch Top React Native Developer Poland 2022](https://railwaymen.org/assets/awards/ClutchTopReactNativePoland_2022-a50094d73ac73fec5c868c5544048db746c9a086fcbe9e7dcf3644875c47762c.png)](https://clutch.co/profile/railwaymen)[![Clutch Top Ruby on Rails Developer Poland 2022](https://railwaymen.org/assets/awards/ClutchTopRubyOnRailsPoland_2022-dc90eec21384445755158dd53914b6e3ef947e75cfe6dba521822c73bd64b789.png)](https://clutch.co/profile/railwaymen)[![Clutch Top Software Developer Fintech 2022](https://railwaymen.org/assets/awards/ClutchTopSoftwareDeveloperFintech_2022-ba75658f45c04d38d0fa4f9dcbfc78e2982b62222d681d6dc3f2f40fe2cafc9b.png)](https://clutch.co/profile/railwaymen)[![Clutch B2B Services 2022](https://railwaymen.org/assets/awards/Best-PerformingB2B2022-4a7057260a703088e644083b31320fe6fdafbfe3491eadf7e9a711fa9e3f9174.png)](https://clutch.co/profile/railwaymen)

[![Clutch Recognition Best App Development Company](https://railwaymen.org/assets/awards/TheClutch1000-a5cd5e3433659ee45539838fa945002f147b6ed9065166f8ba9ff56d216173eb.png)](https://blog.railwaymen.org/railwaymen-named-global-leaders-top-10-ruby-on-rails-developers-2018?_gl=1*1lggq91*_gcl_au*MTY4NzY2MDQ5Mi4xNzMxNDAxMDg4*_ga*MTY1MzUxNjI1Ni4xNzMxNDAxMDg4*_ga_1TW68M8Z6C*MTczMjcwMDE4Ny4xNi4xLjE3MzI3MDExMzYuMzIuMC4w)[![Top Software Development Company](https://railwaymen.org/assets/awards/Custom-Software-Development-Companies-1c56b8d73fbc48c21514311021c65f85a53cd955a3f910a9c2347a6c4a934b0f.png)](https://www.softwareworld.co/top-custom-software-development-companies/)[![Hire elite software development vendors at Pangea](https://railwaymen.org/assets/awards/Pangea-3db009da8ad6d19dfdafc66c51d16928730a715c3195776579bff5e0df4c13d4.png)](https://www.pangea.ai/vendors/railwaymen/)[![GoodFirms Badge](https://railwaymen.org/assets/awards/goodfirms-6880d7b6b80ee00d7189656a8236466571c5f94f146a8d42f5421d85f53b05df.svg)](https://www.goodfirms.co/company/railwaymen)[![Digital Knights](https://railwaymen.org/assets/awards/dk-8e9cb01c4fb52cd6dd812212e5d6925772aa6399c71d47387e3f8a8d5d58ac59.svg)](https://www.digitalknights.co/)

Railwaymen locations

- Kraków
  
  Na Zjeździe 11, 30-527
- San Francisco
  
   Silicon Valley Acceleration Center. 180 Sansome Street

 You can change your cookie settings at any time Close and don't show again

© 2026 Railwaymen

```json
{
  "@context" : "https://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "Michał Szymański, Senior RoR Developer",
    "url" : "https://blog-hubspot.railwaymen.org/author/michał-szymanski-senior-ror-developer"
  },
  "dateModified" : "2025-04-01T11:13:01.223Z",
  "datePublished" : "2020-02-25T11:49:22.000Z",
  "headline" : "Golang Tutorial - How to Implement CLI App in 4 Steps Using Cobra?",
  "image" : [ "https://blog-hubspot.railwaymen.org/hubfs/golang%20tutorial%20for%20beginners%20(1).jpg" ],
  "mainEntityOfPage" : {
    "@id" : "https://blog-hubspot.railwaymen.org/golang-tutorial-how-to-implement-cli-app-in-4-steps-using-cobra-library",
    "@type" : "WebPage"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://blog-hubspot.railwaymen.org/hubfs/new%20website/rwm%20logotype.png"
    },
    "name" : "Railwaymen Sp. z o.o."
  }
}
```