Table of Contents
Create a module
Create a command line entry
Cobra code routine
Create subcommand
Add function code
Compile and test
Summary
Home Backend Development Golang A common golang library cobra

A common golang library cobra

May 13, 2021 am 11:53 AM
golang

The following tutorial column from golang will introduce you to cobra, a common golang library. I hope it will be helpful to friends in need!

cobra is a library in the go language that can be used to write command line tools. Usually we can see git pull , docker container start , apt install and other commands, which can be easily implemented with corba. In addition, go language It is easy to compile into a binary file. This article will implement a simple command line tool.

Write a specific example, design a command called blog, with four sub-commands

 blog new [post-name] :创建一篇新的blog
 blog list   :列出当前有哪些文章
 blog delete [post-name]: 删除某一篇文章
 blog edit [post-name]:编辑某一篇文章
Copy after login

The plan has the following steps

  • create Module
  • Use cobra’s command line to create a command line entry
  • Use cobra’s command line to create subcommands
  • Write functional logic

Create a module

$ go mod init github.com/shalk/blog
go: creating new go.mod: module github.com/shalk/blog
Copy after login

Create a command line entry

Speaking of the command line, you may think of bash’s getopt or java’s jcommand, which can parse various styles of command lines, but usually these command lines There is a fixed way of writing. Generally, if you can’t remember this way of writing, you need to find a template and refer to the following. In addition to parsing the command line, cobra also provides a command line that can generate templates. Install this command line first, and add the library dependencies to go.mod

$ go get -u github.com/spf13/cobra/cobra
Copy after login

cobra will be installed in the $GOPATH\bin directory. Pay attention to adding it to the PATH in the environment variable.

$ cobra init --pkg-name github.com/shalk/blog -a shalk -l mit
Your Cobra applicaton is ready at
D:\code\github.com\shalk\blog
Copy after login

The directory structure is as follows:

./cmd
./cmd/root.go
./go.mod
./go.sum
./LICENSE
./main.go
Copy after login

Compile it

go build  -o blog .
Copy after login

Execute it

$blog -h
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.
Copy after login

The command line will be created. It seems that you don’t need to write a single line of code. , because as the understanding deepens, the generated code needs to be adjusted later, so it is still necessary to understand the routine of cobra code.

Cobra code routine

There are three concepts, command, flag and args, for example:

go get -u test.com/a/b
Copy after login

Here get is commond (this is more special), -u is flag, test.com/a/b is args

Then the command line is composed of three parts, so it is necessary to define some basic information of the

  • command itself, represented by command, and the specific object They are some features or options of the cobra.Command
  • command, represented by flag. The specific object is the last parameter of flag.FlagSet
  • , represented by args, usually []string

Another concept is subcommands. For example, get is the subcommand of go. This is a tree-structured relationship.

I can use the go command, or I can use the go get command

For example: root.go defines the root command, and also defines the flag in init. If it is specifically executed, Just fill in the Run field.

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "blog",
	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) { },
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.

	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.blog.yaml)")

	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

}
Copy after login

If you need subcommands, you need to give rootCmd.AddCommand() other commands in init. Other subcommands are usually written in a separate file and have a global variable so that rootCmd can add it

Create subcommand

D:\code\github.com\shalk\blog>cobra add  new
new created at D:\code\github.com\shalk\blog

D:\code\github.com\shalk\blog>cobra add  delete
delete created at D:\code\github.com\shalk\blog

D:\code\github.com\shalk\blog>cobra add  list
list created at D:\code\github.com\shalk\blog

D:\code\github.com\shalk\blog>cobra add  edit
edit created at D:\code\github.com\shalk\blog
Copy after login

New.go, delete.go,list.go,edit.go

Add function code

new.go

var newCmd = &cobra.Command{
	Use:   "new",
	Short: "create new post",
	Long:  `create new post `,
	Args: func(cmd *cobra.Command, args []string) error {
		if len(args) != 1 {
			return errors.New("requires a color argument")
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		fileName := "posts/" + args[0]
		err := os.Mkdir("posts", 644)
		if err != nil {
			log.Fatal(err)
		}
		_, err = os.Stat( fileName)
		if os.IsNotExist(err) {
			file, err := os.Create(fileName)
			if err != nil {
				log.Fatal(err)
			}
			log.Printf("create file %s", fileName)
			defer file.Close()
		} else {
		}
	},
}
Copy after login

list.go

var listCmd = &cobra.Command{
	Use:   "list",
	Short: "list all blog in posts",
	Long: `list all blog in posts `,
	Run: func(cmd *cobra.Command, args []string) {
		_, err := os.Stat("posts")
		if os.IsNotExist(err) {
			log.Fatal("posts dir is not exits")
		}
		dirs, err := ioutil.ReadDir("posts")
		if err != nil {
			log.Fatal("read posts dir fail")
		}
		fmt.Println("------------------")
		for _, dir := range dirs {
			fmt.Printf(" %s\n", dir.Name() )
		}
		fmt.Println("------------------")
		fmt.Printf("total: %d blog\n", len(dirs))

	},
}
Copy after login

delete.go

var deleteCmd = &cobra.Command{
	Use:   "delete",
	Short: "delete a post",
	Long: `delete a post`,
	Args: func(cmd *cobra.Command, args []string) error {
		if len(args) != 1 {
			return errors.New("requires a color argument")
		}
		if strings.Contains(args[0],"/") || strings.Contains(args[0],"..") {
			return errors.New("posts name should not contain / or .. ")
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		fileName := "./posts/" +  args[0]
		stat, err := os.Stat(fileName)
		if os.IsNotExist(err) {
			log.Fatalf("post %s is not exist", fileName)
		}
		if stat.IsDir() {
			log.Fatalf("%s is dir ,can not be deleted", fileName)
		}
		err = os.Remove(fileName)
		if err != nil {
			log.Fatalf("delete %s fail, err %v", fileName, err)
		} else {
			log.Printf("delete post %s success", fileName)
		}
	},
}
Copy after login

edit.go This is a little troublesome, because if you call a program such as vim to open the file , and the golang program itself needs to detach to exit. Let’s put it aside for now (TODO)

Compile and test

I am testing on window, Linux is simpler

PS D:\code\github.com\shalk\blog> go build -o blog.exe .
PS D:\code\github.com\shalk\blog> .\blog.exe list
------------------
------------------
total: 0 blog
PS D:\code\github.com\shalk\blog> .\blog.exe new blog1.md
2020/07/26 22:37:15 create file posts/blog1.md
PS D:\code\github.com\shalk\blog> .\blog.exe new blog2.md
2020/07/26 22:37:18 create file posts/blog2.md
PS D:\code\github.com\shalk\blog> .\blog.exe new blog3.md
2020/07/26 22:37:20 create file posts/blog3.md
PS D:\code\github.com\shalk\blog> .\blog list
------------------
 blog1.md
 blog2.md
 blog3.md
------------------
total: 3 blog
PS D:\code\github.com\shalk\blog> .\blog delete blog1.md
2020/07/26 22:37:37 delete post ./posts/blog1.md success
PS D:\code\github.com\shalk\blog> .\blog list
------------------
 blog2.md
 blog3.md
------------------
total: 2 blog
PS D:\code\github.com\shalk\blog> ls .\posts\


    目录: D:\code\github.com\shalk\blog\posts


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        2020/7/26     22:37              0 blog2.md
-a----        2020/7/26     22:37              0 blog3.md


PS D:\code\github.com\shalk\blog>
Copy after login

Summary

cobra is an efficient command line The parsing library uses cobra's scaffolding to quickly implement a command line tool. If you need more detailed control, you can refer to cobra's official documentation.

The above is the detailed content of A common golang library cobra. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to find the first substring matched by a Golang regular expression? How to find the first substring matched by a Golang regular expression? Jun 06, 2024 am 10:51 AM

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Golang framework development practical tutorial: FAQs Golang framework development practical tutorial: FAQs Jun 06, 2024 am 11:02 AM

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.

How to use predefined time zone with Golang? How to use predefined time zone with Golang? Jun 06, 2024 pm 01:02 PM

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

See all articles