关于go:go-命令行工具库-cobra-使用入门

5次阅读

共计 1351 个字符,预计需要花费 4 分钟才能阅读完成。

一、介绍

cobra 库是 go 最罕用的命令行库。
开原地址:https://github.com/spf13/cobra

二、疾速应用

1、新建目录

mkdir cobratest  &&  cd cobratest

2、初始化 go mod

go mod init sample/cobratest

此时咱们关上 go.mod 第一行写了咱们的包名为 sample/cobratest

module sample/cobratest

go 1.14

require (
    github.com/inconshreveable/mousetrap v1.0.1 // indirect
    github.com/spf13/cobra v1.5.0 // indirect
)

3、装置 cobra

go get -u github.com/spf13/cobra@latest

4、cobra 初始化

cobra init --pkg-name sample/cobratest

咱们关上命令行应用 tree 命令看一下文件目录

➜  cobratest git:(master) ✗ tree
.
├── LICENSE
├── cmd
│   └── root.go
├── go.mod
├── go.sum
└── main.go

1 directory, 5 files

5、新建一个子命令

cobra add cronMyFirst

咱们会发现在 cmd 目录同级 root.go 生成了一个新的文件 cronMyFirst.go
关上 cronMyFirst.go 文件

package cmd

import (
    "fmt"

    "github.com/spf13/cobra"
)

// cronMyFirstCmd represents the cronMyFirst command
var cronMyFirstCmd = &cobra.Command{
    Use:   "cronMyFirst",
    Short: "A brief description of your command",
    Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. 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.`,
    Run: func(cmd *cobra.Command, args []string) {fmt.Println("cronMyFirst called")
    },
}

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

下面有一个 Use: “cronMyFirst”, 也就是咱们应用的时候 只有执行 cronMyFirst 就行了。

6、应用一下 cronMyFirst

 go run ./main.go cronMyFirst

输入:

cronMyFirst called

应用胜利,当然咱们也能够编译后再应用,如下:

 go build -o cobratest ./main.go
 ./cobratest cronMyFirst

输入如下:

cronMyFirst called
正文完
 0