您现在的位置是:群英 > 开发技术 > 编程语言
GO语言的cobra库有什么用,用法是怎样
Admin发表于 2022-05-20 17:25:55852 次浏览
这篇文章给大家分享的是“GO语言的cobra库有什么用,用法是怎样”,文中的讲解内容简单清晰,对大家学习和理解有一定的参考价值和帮助,有这方面学习需要的朋友,接下来就跟随小编一起学习一下“GO语言的cobra库有什么用,用法是怎样”吧。

cobra 是 go 语言的一个库,可以用于编写命令行工具。通常我们可以看到git pulldocker container start apt install 等等这样命令,都可以很容易用corba来实现,另外,go 语言是很容易编译成一个二进制文件,本文将实现一个简单的命令行工具。

具体写一个例子, 设计一个命令叫blog, 有四个子命令

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

计划有以下几个步骤

  • 创建模块
  • 用cobra的命令行,创建命令行入口
  • 用cobra的命令行,创建子命令
  • 编写功能逻辑

创建模块

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

创建命令行入口

说到命令行,可能会想到bash的getopt 或者 java 的jcommand,可以解析各种风格的命令行,但是通常这些命令行都有固定的写法,这个写法一般还记不住要找一个模板参考以下。cobra除了可以解析命令行之外,还提供了命令行,可以生成模板。先安装这个命令行, 并且把库的依赖加到go.mod里

$ go get -u github.com/spf13/cobra/cobra

cobra会安装到$GOPATH\bin 目录下,注意环境变量中把它加入PATH中

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

目录结构如下:

./cmd
./cmd/root.go
./go.mod
./go.sum
./LICENSE
./main.go

编译一下

go build  -o blog .

执行一下

$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.

命令行就创建好了,看上去一行代码也不用写,由于随着了解的深入,后面需要调整生成的代码,还是要了解一下cobra代码的套路。

cobra代码的套路

有三个概念,command、flag和args ,例如:

go get -u test.com/a/b

这里 get 就是commond(这里比较特殊), -u 就是flag, test.com/a/b 就是args

那么命令行就是有三部分构成,所以需要定义好这个

  • 命令自身的一些基本信息,用command表示,具体对象是 cobra.Command
  • 命令的一些标致或者选项,用flag表示,具体对象是 flag.FlagSet
  • 最后的参数,用args表示,通常是[]string

还有一个概念是子命令,比如get就是go的子命令,这是一个树状结构的关系。

我可以使用go命令,也可以使用 go get命令

例如: root.go,定义了root命令,另外在init里面 定义了flag,如果它本身有具体执行,就填充Run字段。

// 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")

}

如果需要子命令,就需要在init 里,给 rootCmd.AddCommand() 其他的command,其他的子命令通常也会单独用一个文件编写,并且有一个全局变量,让rootCmd可以add它

创建子命令

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

cmd 目录下增加了 new.go, delete.go,list.go,edit.go

增加功能代码

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 {
		}
	},
}

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))

	},
}

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)
		}
	},
}

edit.go 这个有一点麻烦,因为如果调用一个程序比如vim 打开文件,并且golang程序本身要退出,需要detach。暂时放一下(TODO)

编译测试

我是window测试,linux 更简单一点

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>

小结

cobra 是一个高效的命令行解析库,利用cobra的脚手架,可以快速的实现一个命令行工具。如果需要更细致的控制,可以参考cobra的官方文档。


以上就是关于“GO语言的cobra库有什么用,用法是怎样”的相关知识,感谢各位的阅读,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注群英网络,小编每天都会为大家更新不同的知识。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

标签: cobra库
相关信息推荐
2022-05-17 17:06:33 
摘要:Django具有完整的封装,开发者可以高效率的开发项目,Django将大部分的功能进行了封装,开发者只需要调用即可,接下来通过本文给大家介绍基于Anaconda搭建Django环境的教程,需要的朋友可以参考下
2022-05-27 18:02:26 
摘要:spring aop原理:1、AOP 面向切面,是一种编程范式,提供从另一个角度来考虑程序结构以完善面向对象编程OOP;2、AOP为开发者提供了一种描述横切关注点的机制,并能够自动将横切关注点织入到面向对象的软件系统中。
2022-08-31 17:23:52 
摘要:在js中,可以使用getElementsByClassName方法获得同一类名的多个input对象。下面给大家举例讲解js如何通过类名获得多个input对象。
云活动
推荐内容
热门关键词
热门信息
群英网络助力开启安全的云计算之旅
立即注册,领取新人大礼包
  • 联系我们
  • 24小时售后:4006784567
  • 24小时TEL :0668-2555666
  • 售前咨询TEL:400-678-4567

  • 官方微信

    官方微信
Copyright  ©  QY  Network  Company  Ltd. All  Rights  Reserved. 2003-2019  群英网络  版权所有   茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078   粤ICP备09006778号
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
微信公众号
返回顶部
返回顶部 返回顶部